Question

I want to read a sequence of frames from any folder using openCV. All frames are in sequence i.e. (1).jpg,(2).jpg,.... I tried

VideoCapture cap;
cap.open("Directory/");
for(;;)
    {
        Mat frame;
        cap >> frame;
    }

but it doesn't work. This question has been asked before but i don't know why this answer doesn't work for me.

OpenCV: Reading image series from a folder

do i need to rename the images?.

Was it helpful?

Solution

cap open should be cap.open("Directory/(%02d).jpg"); and you have to rename your images so that they look like (01).jpg,(02).jpg etc so that they have fixed length. if the images are like (001).jpg then you should use `cap.open("Directory/(%03d).jpg");

edit

#include "opencv2/opencv.hpp"
using namespace cv;
int main()
{
    VideoCapture cap;
    cap.open("imgs/(%02d).jpg");
    int i=0;
    for(;;)
    {
        if(i++%37==0)cap=VideoCapture("imgs/(%02d).jpg");//there are 37 frames in the dir
        Mat frame;
        cap >> frame;
        imshow("frame",frame);
        if(waitKey(1)==27)
            exit(0);
    }
    return 0;
}

OTHER TIPS

Try to prepare an xml/yaml file with list of names with path to the images, in the desired order. Then load the list as a vector or some resembling structure, and then open them one by one in a loop.

Here the full code to do read a sequence of frames with five zeros in name "frame00000.jpg, frame00001.jpg,.....,frame00010.jpg...) using string concatination idea just like matlab.

#include "stdafx.h"
#include <stdlib.h>
#include <math.h>
#include <opencv/cv.h>      // include it to used Main OpenCV functions.
#include <opencv/highgui.h> //include it to use GUI functions.

using namespace std;
using namespace cv;

string intToStr(int i,string path){
    string bla = "00000";
    stringstream ss;
    ss<<i;
    string ret ="";
    ss>>ret;
    string name = bla.substr(0,bla.size()-ret.size());
    name = path+name+ret+".jpg";
    return name;
    }


int main(int, char**)
    {   
    string previous_window = "Previous frame";
    string current_window = "Current frame ";

    int i=0;
    for(int i = 1 ; i< 10 ; i++)
    {
        Mat Current, Previous;
        string Curr_name = intToStr(i,"D:/NU/Junior Scientist/Datasets/egtest04/frame");
        string Prev_name = intToStr(i-1,"D:/NU/Junior Scientist/Datasets/egtest04/frame");
        Current = imread(Curr_name,1);
        Previous = imread(Prev_name,1);

        namedWindow(current_window,WINDOW_AUTOSIZE);
        namedWindow(current_window,WINDOW_AUTOSIZE);
        imshow(current_window,Current);
        imshow(previous_window,Previous);
        waitKey(0);
    }
    }

Where "D:/NU/Junior Scientist/Datasets/egtest04/frame" is the path sting.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top