在opencv中的文件夹中覆盖图像序列

时间:2013-01-31 03:47:28

标签: c++ visual-studio-2010 opencv

在C ++中使用VS 2010并尝试将其置于for循环中

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

这些是出现的文件名:

ropped_.jpg
opped_.jpg
pped_.jpg

我该怎么办?如何将它们放在与我的源代码相同的目录中的文件夹中?

4 个答案:

答案 0 :(得分:11)

您可以使用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);

要创建新文件夹,您可以在mkdir的{​​{1}}函数中使用Windows命令system

stdlib.h

答案 1 :(得分:3)

    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的答案的更长版本

答案 2 :(得分:2)

试试这个:

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);

答案 3 :(得分:0)

因为这是Google搜索的第一个结果,所以我将使用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);
}
相关问题