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 filenames that came out:
ropped_.jpg
opped_.jpg
pped_.jpg
How do I do it? And how do I put them in a folder in the same directory as my source code?
You can use std::stringstream
to build sequential file names:
First include the sstream
header 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 new folder, you can use windows' command mkdir
in the system
function 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);
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
Try this:
char file_name[100];
sprintf(file_name, "cropped%d.jpg", ct + 1);
imwrite(file_name, img_cropped);
They should just go in the directory where you run your code, otherwise, you'll have to manually specify like this:
sprintf(file_name, "C:\path\to\source\code\cropped%d.jpg", ct + 1);
Since this is the first result for a google search I will add my answer using std::filesystem (C++17)
std::filesystem::path root = std::filesystem::current_path();
std::filesystem::create_directories(root / "my_images");
for (int num_image = 0; num_image < 10; num_image++){
// Perform some operations....
cv::Mat im_out;
std::stringstream filename;
filename << "my_images"<< "/" << "image" << num_image << ".bmp";
cv::imwrite(filename.str(), im_out);
}