Reading an ordered sequence of images in a folder using OpenCV

前端 未结 1 848
攒了一身酷
攒了一身酷 2020-12-11 09:11

I have this following example code, where I\'m displaying my webcam.

But how can I display a sequence of pictures in a folder like:

0.jpg 
1.jpg 
2.j         


        
1条回答
  •  借酒劲吻你
    2020-12-11 09:29

    1) You can use VideoCapture with a filename:

    filename – name of the opened video file (eg. video.avi) or image sequence (eg. img_%02d.jpg, which will read samples like img_00.jpg, img_01.jpg, img_02.jpg, ...)

    2) Or simply change the name of the image to load according to a counter.

    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        std::string folder = "your_folder_with_images";
        std::string suffix = ".jpg";
        int counter = 0;
    
        cv::Mat myImage;
    
        while (1)
        {
            std::stringstream ss;
            ss << std::setw(4) << std::setfill('0') << counter; // 0000, 0001, 0002, etc...
            std::string number = ss.str();
    
            std::string name = folder + number + suffix;
            myImage = cv::imread(name);
    
            cv::imshow("HEYO", myImage);
            int c = cv::waitKey(1);
    
            counter++;
        }
        return 0;
    }
    

    3) Or you can use the function glob to store all the filenames matching a given pattern in a vector, and then scan the vector. This will work also for non-consecutive numbers.

    #include 
    using namespace cv;
    
    int main()
    {
        String folder = "your_folder_with_images/*.jpg";
        vector filenames;
    
        glob(folder, filenames);
    
        Mat myImage;
    
        for (size_t i = 0; i < filenames.size(); ++i)
        {
            myImage = imread(filenames[i]);
            imshow("HEYO", myImage);
            int c = cv::waitKey(1);
        }
    
        return 0;
    }
    

    0 讨论(0)
提交回复
热议问题