Imwrite sequence of images in a folder in opencv

Using VS 2010 in C ++ and tried to put this in a for loop

String filename = "cropped_" + (ct+1);
imwrite(filename + ".jpg", img_cropped);

      

These are the names of the files that came out:

ropped_.jpg
opped_.jpg
pped_.jpg

      

How should I do it? And how do I put them in a folder in the same directory as the source code?

+3


source to share


3 answers


You can use std::stringstream

to create sequential filenames:

First include the header sstream

from the C ++ Standard Library.

#include<sstream>

using namespace std;

      

Then, inside your code, you can do the following:



stringstream ss;

string name = "cropped_";
string type = ".jpg";

ss<<name<<(ct + 1)<<type;

string filename = ss.str();
ss.str("");

imwrite(filename, img_cropped);

      

To create a new folder, you can use the windows command mkdir

in a function system

from stdlib.h

:

 string folderName = "cropped";
 string folderCreateCommand = "mkdir " + folderName;

 system(folderCreateCommand.c_str());

 ss<<folderName<<"/"<<name<<(ct + 1)<<type;

 string fullPath = ss.str();
 ss.str("");

 imwrite(fullPath, img_cropped);

      

+10


source


Try the following:

char file_name[100];
sprintf(file_name, "cropped%d.jpg", ct + 1);
imwrite(file_name, img_cropped);

      



They should just go into the directory where you run your code, otherwise you'll have to manually specify it like this:

sprintf(file_name, "C:\path\to\source\code\cropped%d.jpg", ct + 1);

      

+2


source


    for (int ct = 0; ct < img_SIZE ; ct++){
    char filename[100];
    char f_id[3];       //store int to char*
    strcpy(filename, "cropped_"); 
    itoa(ct, f_id, 10);
    strcat(filename, f_id);
    strcat(filename, ".jpg");

    imwrite(filename, img_cropped); }

      

By the way, here's a longer version of @ sgar91's answer

+2


source







All Articles