3

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;
}
0

1 Answer 1

4

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;
}
Sign up to request clarification or add additional context in comments.

5 Comments

how to handle it if my images are named 0000, 0001,0002?
0011...0012...0121..0141...and so on
@Bern case 1) img_%04d.jpg, 2) need just a little stream manipulation, or the good old sprintf. See updated snippet, 3) already works
thank you, it works... would it be possible to use my my imread (my sequence of image in a folder) as VideoCapture?
@Bern yes, see option 1) you just need VideoCapture capture("your_folder/%04d.jpg");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.