如何在数组中读取和写入图像?

问题描述 投票:1回答:1

我遇到了如何在名为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);

}

c++ arrays opencv
1个回答
0
投票

假设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);                  
     }
热门问题
推荐问题
最新问题