简体   繁体   English

在 opencv 中的文件夹中写入图像序列

[英]imwrite sequence of images in a folder in opencv

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?以及如何将它们放在与我的源代码相同目录中的文件夹中?

You can use std::stringstream to build sequential file names:您可以使用std::stringstream来构建顺序文件名:

First include the sstream header from the C++ standard library.首先包含来自 C++ 标准库的sstream头文件。

#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 :要创建新文件夹,您可以在stdlib.hsystem函数中使用 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); }

By the way, here's a longer version of @sgar91's answer顺便说一句,这是@sgar91 答案的更长版本

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 (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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM