Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

c++ - Reading an ordered sequence of images in a folder using OpenCV

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.jpg
... and so on 

using imread?

I would like to use that folder as input instead of my webcam.

#include <iostream>    
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>

int main()
{
    cv::VideoCapture capture(0);

    cv::Mat myImage;
    while(1)
    {
        capture>> myImage;

        cv::imshow( "HEYO", myImage);
        int c = cv::waitKey(1);

    }
    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 <opencv2/opencv.hpp>
#include <string>
#include <iomanip>
#include <sstream>

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 <opencv2/opencv.hpp>
using namespace cv;

int main()
{
    String folder = "your_folder_with_images/*.jpg";
    vector<String> 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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...