如何从源文件夹中连续读取图像?


我的程序由以下步骤组成:
1. 从源文件夹中读入任何新图像
2. 处理图像(检测对象并校正它们)
3. 将校正对象图像保存在目标文件夹中
…重复

这个想法是,在扫描邮票时,程序单独输出每个邮票,或者如果邮票聚集在一起,则将其分组。 用户应该能够在处理过程中连续进行扫描。

该程序根据检测目标文件夹中新图像的三种方式以三种不同的方式运行。 实际中只会使用第三种方式。 前两个有望帮助解释正在发生的事情及其原因。

1. 拖放
手动将图像拖放到文件夹中时一切正常; 我可以无限期地这样做,并且输出是正确的。

2.复制粘贴
当在目标文件夹中本地复制并粘贴图像时,程序立即停止,显示以下异常:

System.IO.IOException: 'Unable to access the file xxx because it is being used by another process.'

在目标文件夹中复制粘贴图像时也会出现同样的异常。

3. 扫描程序的输出
我使用 ScanSnap SV600,它将未处理的印章扫描保存在目标文件夹中。 现在出现了令我困惑的情况:我的处理程序的行为发生了变化。 每次我在调试模式下启动程序时,第一次扫描总是成功。 但是,如果前一个调试会话成功,则在处理程序的同一运行中读取后续扫描会失败。 换句话说:程序有二分之一的行为符合预期。 而其他时候它会在第二次扫描时停止,给我上述错误。

为了检测新图像,我使用:

C#
var fileSystemWatcher = new FileSystemWatcher(@inputDir)
{
    Filter = "*.jpg",
    NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite,
    EnableRaisingEvents = true
};
fileSystemWatcher.Created += new FileSystemEventHandler(OnFileCreated);

我尝试过的:

此外,这是处理开始之前代码的一部分。 它不是最漂亮的,并且使用“Thread.Sleep()”感觉有点“hacky”。 也许这是一个线索?

C#
private void OnFileCreated(object sender, FileSystemEventArgs e)
{
    sw.Restart();
    string imagePath = e.FullPath;
    inputFiles.AddToQ(imagePath);
    Console.WriteLine("{0} is queued.", e.FullPath);

    int number = 0;
    if (!int.TryParse(setCluster.Text.Trim(), out number))
    {
        MessageBox.Show("Please enter a valid number for Clustering.");
        setCluster.Text = "20";
    }
    else
    {
        while (inputFiles.Inspect() != imagePath) Thread.Sleep(100);
        try
        {
            lock (locker)
            {
                Bitmap incoming = new Bitmap(inputFiles.Process());
                Console.WriteLine("{0} is being processed.", e.FullPath);

                if (currentScan.Image != null) currentScan.Image = null;
                currentScan.Invoke((Action)
                delegate ()
                {
                    currentScan.Image = (Image)new Bitmap(e.FullPath);
                    currPathText.Text = imagePath;
                });

                // processing step
                Bitmap resized = new Bitmap(incoming, new
                    Size(Convert.ToInt32(incoming.Width / Variables.ScalingFact),
                    Convert.ToInt32(incoming.Height / Variables.ScalingFact)));
                .....

解决方案1

这很简单。 您试图在复制过程完成并关闭文件之前读取该文件。

您只需尝试打开该文件即可。 如果它因已在使用而引发异常,请稍等一下,然后重试。 继续尝试,直到您打开文件或耗尽您任意选择的重试限制。

コメント

タイトルとURLをコピーしました