C++ OpenCV:如何对带有图像的文件夹执行批处理?

C++ OpenCV:如何对带有图像的文件夹执行批处理?,c++,multithreading,opencv,c++11,C++,Multithreading,Opencv,C++11,我有一个图像文件夹,我对它们执行一些基本操作的顺序: 加载源图像 对图像执行一些图像处理 保存结果图像 所以我想在单独的线程中处理每个图像,以加快处理速度 下面是我的示例代码: ThreadExample.h #include <thread> class ThreadProcessing { static unsigned int concurentThreadsSupported; static void ImagePro

我有一个图像文件夹,我对它们执行一些基本操作的顺序:

  • 加载源图像
  • 对图像执行一些图像处理
  • 保存结果图像
  • 所以我想在单独的线程中处理每个图像,以加快处理速度

    下面是我的示例代码:

    ThreadExample.h

    #include <thread>
    
    
        class ThreadProcessing
        {
             static unsigned int concurentThreadsSupported;
    
             static void ImageProcessingFunction(const std::string &input_dir, const std::string &filename);
        public:
             void PrintNumberOfCPU();
             void MultithreadingProcessing(const std::string &dir, int N);
             void SingleThreadProcessing(const std::string &dir);
        };
    
    main.cpp

        #include "ThreadExample.h"
    
        unsigned int ThreadProcessing::concurentThreadsSupported = std::thread::hardware_concurrency();
    
        using namespace std;
    
        void ThreadProcessing::PrintNumberOfCPU()
        {
            cout << "Number of CPU : " << concurentThreadsSupported << endl;
        }
    
    void ThreadProcessing::ImageProcessingFunction(const string &input_dir, const string &filename)
        {
            Mat src= imread(input_dir+"/"+filename);
            Mat dst;
    
            for(int i=0; i<10; ++i)
            {
                medianBlur(src, dst, 71);
            }
    
            boost::filesystem::path name= path(filename).stem();
    
            string output_filename= (input_dir/name).string()+"_output.png";
            imwrite(output_filename, dst);
        }
    
        void ThreadProcessing::SingleThreadProcessing(const string &dir)
        {
            time_t SingleThreadProcessingTime = clock();
    
            vector<string> imageNames= GetAllFilenamesInDir(dir, ".jpg");
    
            for(int i=0; i<(int)imageNames.size(); ++i)
            {
                ImageProcessingFunction(dir, imageNames[i]);
            }
    
            SingleThreadProcessingTime = clock() - SingleThreadProcessingTime;
            cout << "SingleThreadProcessingTime : " << (float(SingleThreadProcessingTime) / CLOCKS_PER_SEC) << endl;
        }
    
        void ThreadProcessing::MultithreadingProcessing(const string &dir, int N)
        {
            time_t MultithreadingProcessingTime = clock();
    
            std::thread threads[N];
    
            bool isAllImageProcessed= false;
            vector<string> imageNames= GetAllFilenamesInDir(dir, ".jpg");
    
            for(int i=0; i<(int)imageNames.size();)
            {
                //Launch a group of threads
                for(int k= 0; k< N; ++k)
                {
                    threads[k] = std::thread(ImageProcessingFunction, dir, imageNames[i]);
    
                    i++;
    
                    if(i>=(int)imageNames.size())
                    {
                        N= k+1;
                        isAllImageProcessed= true;
                        break;
                    }
                }
    
                //Join the threads with the main thread
                for(int k= 0; k< N; ++k)
                {
                    threads[k].join();
                }
    
                if(isAllImageProcessed)
                    break;
            }
    
            MultithreadingProcessingTime = clock() - MultithreadingProcessingTime;
            cout << "MultithreadingProcessingTime : " << (float(MultithreadingProcessingTime) / CLOCKS_PER_SEC) << endl;
        }
    
    int main(int argc, char** argv)
    {
        ThreadProcessing threadProcessing;
        threadProcessing.PrintNumberOfCPU();
        threadProcessing.SingleThreadProcessing("/home/user/Images");
        threadProcessing.MultithreadingProcessing("/home/user/Images", 1);
        cout << "Done." << endl;
        return 0;
    }
    
    当我使用4个线程时,输出为:

    Number of CPU : 8
    SingleThreadProcessingTime : 6.54173
    MultithreadingProcessingTime : 6.73393
    Done.
    
    Number of CPU : 8
    SingleThreadProcessingTime : 6.39089
    MultithreadingProcessingTime : 8.3365
    Done.
    
    我的代码有问题还是概念上有问题

    更新:

    我还尝试了两种变体:

  • 每个映像1个线程-似乎这种方法可以达到操作系统的最大线程数限制?而且效率也很低
  • 代码:

    更新2:

    我还做了一个没有IO操作的测试,只有图像处理

    代码:

    正如我们所看到的,
    real
    时间更小

    因此,以前的结果应该是:

    SingleThreadProcessingTime : 13.6235
    
    real    0m13.845s
    user    0m13.932s
    sys 0m0.280s
    
    MultithreadingProcessingTime : 21.0902
    
    real    0m3.584s
    user    0m20.356s
    sys 0m1.316s
    
    SingleThreadForEachImageTime : 23.961
    
    real    0m3.370s
    user    0m22.584s
    sys 0m1.976s
    
    EachThreadProcessChunkOfImagesTime : 20.7885
    
    real    0m3.433s
    user    0m20.292s
    sys 0m1.116s
    
    那么多线程代码的执行时间应该如何衡量呢

    更新:找到答案

    我需要使用
    挂钟时间
    而不是
    cpu时间

    以下是正确的结果:

    SingleThreadProcessing :  WALLCLOCK TIME: 13.8245 seconds
    MultithreadingProcessing :  WALLCLOCK TIME: 4.1977 seconds
    SingleThreadForEachImage :  WALLCLOCK TIME: 3.25084 seconds
    EachThreadProcessChunkOfImages :  WALLCLOCK TIME: 3.36626 seconds
    OnlyProcessingTimeSequential :  WALLCLOCK TIME: 2.36041 seconds
    OnlyProcessingTimeMultithread :  WALLCLOCK TIME: 0.706921 seconds
    

    正如在中明确指出的,当涉及到单个磁盘上的I/O操作时,多线程确实没有效率。线程所做的大部分工作都是I/O操作

    由于创建线程和
    join()
    操作导致函数的多线程版本变慢,您可能会受到磁盘速度的限制,并承受开销

    编辑:


    正如@Dan Mašek在评论中所说的,大部分时间实际上都花在了压缩上。改进流程的一种方法是创建一个线程,从磁盘读取图像并将其提供给其他工作线程(可能通过
    队列
    ,请参阅)。通过这种方式,您可以按顺序阅读,但繁重的任务是由许多工作人员完成的。

    对于一个图像,每个图像启动一个线程,然后等待所有线程完成,然后再对另一组图像执行此操作,这是非常低效的。你为什么不把文件列表分成8个部分,然后把列表的整个部分都给每个线程呢?另外,请尽量减少您的示例—不需要所有注释掉的行。@DanMašek我尝试了您的建议,没有加速,请参阅更新。今天晚些时候我将进一步研究这个问题。但在这一点上:“每个图像1个线程”——是的,这是一个糟糕的选择。这不是关于操作系统的限制,而是关于硬件——你只有这么多的CPU核心,所以如果有更多的任务,它们必须切换以显示一次运行,切换需要时间。每个线程也需要内存,它们会开始互相破坏缓存,导致进一步的减速等。您的第一个想法是,只运行足够数量的线程来满足当前的CPU计数。你们看过CPU使用率图表了吗?它看起来像什么?对,很好。“…另一方面,如果当前进程是多线程的,并且有多个执行核心可用,
    std::clock
    时间可能比挂钟快。”出于好奇,您只使用8个图像来测试这一点?出于教育目的,尝试使用更多的线程,比如64个,看看相对性能如何变化——您似乎有带超线程的四核CPU,因此8个线程仍然是一个合理的数字。即使在剩下的测试中,也可以使用更多的测试图像来进行适当的测量。也许有一种方法可以以某种智能的方式将IO操作和图像处理操作分开?i、 一些线程加载图像和一些处理它们?看一看。他们详细介绍了一些多线程读取的方法,这些方法可能会对您有所帮助。这取决于图像的大小,但如果图像太大,则可能只有从磁盘读取的速度较慢。在单个磁盘上进行顺序读取是最好的选择。@Sunreef我认为在实际磁盘I/O上花费的时间主要取决于实际压缩图像所花费的时间。确实,使用大小为71的10倍medianBlur在计算上是昂贵的。在这种情况下,让一个线程加载RAM上的所有图像,让其他几个线程处理模糊可以加快整个过程
    SingleThreadProcessingTime : 13.552
    MultithreadingProcessingTime : 15.581
    SingleThreadForEachImageTime : 26.7727
    EachThreadProcessChunkOfImagesTime : 15.9078
    
    void ThreadProcessing::ImageProcessingFunction(const cv::Mat &img)
    {
        Mat dst;
    
        for(int i=0; i<10; ++i)
        {
            medianBlur(img, dst, 71);
        }
    }
        vector<Mat> ThreadProcessing::LoadBatchOfImages(const std::string &dir, int batchSize)
        {
            vector<string> imageNames= GetAllFilenamesInDir(dir, ".jpg");
    
            vector<Mat> imageVec;
            for(int i=0; i<N; ++i)
            {
                string filename= dir+"/"+imageNames[i];
                Mat img= imread(filename);
                imageVec.push_back(img);
            }
    
            return imageVec;
        }
    
        void ThreadProcessing::OnlyProcessingTimeSequential(const std::string &dir, int batchSize)
        {
            //Load batch of images
            vector<Mat> imageVec= LoadBatchOfImages(dir, batchSize);
    
            assert((int)imageVec.size() == batchSize);
            cout << "imageVec.size() : " << imageVec.size() << endl;
    
            time_t OnlyProcessingTimeSequentialTime = clock();
    
            for(int i=0; i<batchSize; ++i)
            {
                ImageProcessingFunction(imageVec[i]);
            }
    
            OnlyProcessingTimeSequentialTime = clock() - OnlyProcessingTimeSequentialTime;
            cout << "OnlyProcessingTimeSequentialTime : " << (float(OnlyProcessingTimeSequentialTime) / CLOCKS_PER_SEC) << endl;
        }
    
        void ThreadProcessing::OnlyProcessingTimeMultithread(const std::string &dir, int batchSize)
        {
            //Load batch of images
            vector<Mat> imageVec= LoadBatchOfImages(dir, batchSize);
    
            assert((int)imageVec.size() == batchSize);
            cout << "imageVec.size() : " << imageVec.size() << endl;
    
            time_t OnlyProcessingTimeMultithread = clock();
    
            std::thread threads[batchSize];
            for(int i=0; i<batchSize; ++i)
            {
                threads[i] = std::thread(ImageProcessingFunction, imageVec[i]);
            }
    
            for(int i=0; i<batchSize; ++i)
            {
                threads[i].join();
            }
    
            OnlyProcessingTimeMultithread = clock() - OnlyProcessingTimeMultithread;
            cout << "OnlyProcessingTimeMultithread : " << (float(OnlyProcessingTimeMultithread) / CLOCKS_PER_SEC) << endl;
        }
    
    imageVec.size() : 8
    OnlyProcessingTimeSequentialTime : 2.34174
    Done.
    
    real    0m2.551s
    user    0m2.640s
    sys 0m0.316s
    
    
    imageVec.size() : 8
    OnlyProcessingTimeMultithread : 4.36681
    Done.
    
    real    0m0.861s
    user    0m4.564s
    sys 0m0.404s
    
    SingleThreadProcessingTime : 13.6235
    
    real    0m13.845s
    user    0m13.932s
    sys 0m0.280s
    
    MultithreadingProcessingTime : 21.0902
    
    real    0m3.584s
    user    0m20.356s
    sys 0m1.316s
    
    SingleThreadForEachImageTime : 23.961
    
    real    0m3.370s
    user    0m22.584s
    sys 0m1.976s
    
    EachThreadProcessChunkOfImagesTime : 20.7885
    
    real    0m3.433s
    user    0m20.292s
    sys 0m1.116s
    
    SingleThreadProcessing :  WALLCLOCK TIME: 13.8245 seconds
    MultithreadingProcessing :  WALLCLOCK TIME: 4.1977 seconds
    SingleThreadForEachImage :  WALLCLOCK TIME: 3.25084 seconds
    EachThreadProcessChunkOfImages :  WALLCLOCK TIME: 3.36626 seconds
    OnlyProcessingTimeSequential :  WALLCLOCK TIME: 2.36041 seconds
    OnlyProcessingTimeMultithread :  WALLCLOCK TIME: 0.706921 seconds