gpt4 book ai didi

c++ - 如何读写数组中的图像?

转载 作者:行者123 更新时间:2023-12-02 10:18:11 24 4
gpt4 key购买 nike

我遇到了有关如何将名为name [j]的数组中的随机图像读写到另一个文件夹的问题。目前,我只能将整个输入目录中的图像读写到另一个目录中,而不是基于数组名[j]的随机图像。我不知道如何将数组中的值传递给imwrite()函数。

这是我的完整代码:

    int main(int argc, char* argv[])
{
string homedir = "C:\\Users\\x\\Documents\\Aggressive\\offline workspace\\abc";
cerr << endl << "path = " << homedir.c_str() << endl;

std::string inputDirectory = "C:\\Users\\x\\Documents\\Aggressive\\offline workspace\\abc";
std::string outputDirectory = "C:\\Users\\x\\Documents\\folder";
DIR* directory = opendir(inputDirectory.c_str());
struct dirent* _dirent = NULL;
int i = 0;
int total;
srand(time(0)); //seed random number

vector<string> name;

if (directory == NULL)
{
printf("Cannot open Input Folder\n");
return 1;
}
while ((_dirent = readdir(directory)) != NULL)
{
puts(_dirent->d_name);
name.push_back(_dirent->d_name);
printf("\n");
i++;

std::string fileName = inputDirectory + "\\" + std::string(_dirent->d_name);
cv::Mat rawImage = cv::imread(fileName.c_str());
if (rawImage.data == NULL)
{
printf("copied\n");
continue;
}
// Add your any image filter here
fileName = outputDirectory + "\\" + std::string(_dirent->d_name);
cv::imwrite(fileName.c_str(), rawImage);


}
//name.erase(name.begin(), name.begin() + 1);

name.erase(name.begin(), name.begin() + 2);
cout << "file name: " << name[16];
total = i - 2;

cout << "\n";
cout << "There's " << total << " files in the current directory.\n" << endl;

cout << "Enter array size: \n";
int a;
cin >> a;


for (int j = 0; j < a; j++) {
//generate random filename
int index = rand() % a;
//cout << filename[index] << endl;

//swap random[j] with random[index]
string temp = name[j];
name[j] = name[index];
name[index] = temp;
}

//loop through array and print value
for (int j = 0; j < a; j++) {
cout << "Random image selected:" << name[j] << endl;
}

closedir(directory);
}

最佳答案

假设name[j]C:\\...\\img.jpg格式的字符串,您可以在每个循环周期中读取这些图像并将它们写入所需的目录。

   for (int j = 0; j < a; j++) {
cout << "Random image selected:" << name[j] << endl;
// name[j] should be in the directory format like "C:\\...\\img.jpg"
//Then read this image
Mat img = imread(name[j]);

//Then write to desired directory in every loop you need to change the name to avoid writing on the same name.
string written_directory = "C:\\Users\\x\\Documents\\folder\\img" + std::to_string(j) + ".jpg";
imwrite(written_directory,img);
}

关于c++ - 如何读写数组中的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61220322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com