程序复制图像在一个文件夹中使用opencv和c++不返回任何东西



使用opencv和c++,我试图编写一个程序,给定一个文件路径,该程序将复制该文件中的每个图像。这是我用imreadimwrite写的:

#include <filesystem>
#include <fstream>
using namespace std;
using namespace cv;
namespace fs = std::filesystem;
Mat duplicateImage(string filename) {
// Load the input image
Mat image = imread(filename, IMREAD_UNCHANGED);
// Create a duplicate image
Mat duplicate = image.clone();
return duplicate;
}
int main(int argc, char** argv)
{

string directory_name = "C:\My\File\Path\Name";
vector<string> files_list;
ifstream file_stream(directory_name);
string line;
while (getline(file_stream, line)) {
files_list.push_back(line);
}
// Duplicate each image in the directory
for (string filename : files_list) {
Mat duplicate = duplicateImage(filename);
string output_filename = filename + "_copy"; // new filename for the duplicate;
cv::imwrite(output_filename, duplicate);
}
}

当我打开文件路径时,没有对文件进行任何更改。

我最初试图用fstream来解决这个问题,导致同样的问题,文件根本没有被修改。任何建议将非常感谢!

编辑:我发现了一个bug -我甚至没有进入for循环,我知道这是因为我做了一个print语句并且没有在conile中看到它。我不确定为什么我不会进入for循环。

你的代码中有两个问题:

1。获取文件列表:

你不能使用ifstreamgetline来获得目录中的文件列表(这就是为什么files_list是空的)。
您可以使用std::filesystem::directory_iterator
在你的例子中应该是这样的:

for (const auto& entry : std::filesystem::directory_iterator(directory_name))
{
files_list.push_back(entry.path().string());
}

2。用cv::imwrite保存图片:

您可以在cv::imwrite文档中看到:

根据文件扩展名选择图像格式(见Cv::imread查看扩展列表)。

详细的扩展列表在这里:cv::imread。其中:.jpg(用于JPEG文件)、.png(用于便携式网络图形)等

因为你添加了"_copy">你的文件名后缀中不再有一个支持的扩展名,并且图像不被保存。

你可以使用"_copy.jpg"或";_copy.png"作为后缀。
您还可以动态地确定当前文件名的扩展名(参见这里:如何在c++中从字符串中获取文件扩展名),并将其添加到生成的文件名中。

然而:

如果您只需要按原样复制图像文件(不修改图像内容),您可以简单地使用std::filesystem::copy而不读取图像内容等。