C++ 在 opencv 中的文件夹中写入图像序列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14618108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
imwrite sequence of images in a folder in opencv
提问by Masochist
Using VS 2010 in C++ and tried to put this in a for loop
在 C++ 中使用 VS 2010 并尝试将其放入 for 循环中
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?
我该怎么做?以及如何将它们放在与我的源代码相同目录中的文件夹中?
回答by sgarizvi
You can use std::stringstream
to build sequential file names:
您可以使用std::stringstream
构建顺序文件名:
First include the sstream
header from the C++ standard library.
首先包含sstream
来自 C++ 标准库的头文件。
#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
:
要创建新文件夹,您可以mkdir
在以下system
函数中使用 windows 的命令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);
回答by Masochist
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
顺便说一句,这是@sgar91 答案的更长版本
回答by Radford Parker
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);
回答by Grillteller
Since this is the first result for a google search I will add my answer using std::filesystem (C++17)
由于这是谷歌搜索的第一个结果,我将使用 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);
}