[英]imwrite sequence of images in a folder in opencv
在 C++ 中使用 VS 2010 並嘗試將其放入 for 循環中
String filename = "cropped_" + (ct+1);
imwrite(filename + ".jpg", img_cropped);
這些是出來的文件名:
ropped_.jpg
opped_.jpg
pped_.jpg
我該怎么做? 以及如何將它們放在與我的源代碼相同目錄中的文件夾中?
您可以使用std::stringstream
來構建順序文件名:
首先包含來自 C++ 標准庫的sstream
頭文件。
#include<sstream>
using namespace std;
然后在您的代碼中,您可以執行以下操作:
stringstream ss;
string name = "cropped_";
string type = ".jpg";
ss<<name<<(ct + 1)<<type;
string filename = ss.str();
ss.str("");
imwrite(filename, img_cropped);
要創建新文件夾,您可以在stdlib.h
的system
函數中使用 windows 的命令mkdir
:
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); }
順便說一句,這是@sgar91 答案的更長版本
試試這個:
char file_name[100];
sprintf(file_name, "cropped%d.jpg", ct + 1);
imwrite(file_name, img_cropped);
它們應該進入您運行代碼的目錄,否則,您必須像這樣手動指定:
sprintf(file_name, "C:\path\to\source\code\cropped%d.jpg", ct + 1);
由於這是谷歌搜索的第一個結果,我將使用 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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.