To read an image that meets the requirements in a folder, you can use the function glob in opencv3.2. The function is defined as follows:
CV_EXPORTS void glob(String pattern, std::vector<String>& result, bool recursive = false);
The first parameter is the path where the file is located, the second parameter is the container that stores the file path, and the third parameter is used to: when recursive is false, only traverse files that match the pattern in the specified folder, and when recursive is true , the subfolders under the specified folder will be traversed at the same time.
The example is as follows, read a tif file in a folder and display
#include <iostream> #include <opencv2/opencv.hpp> using namespace cv; using namespace std; intmain() { vector<String> files; //Store file path vector<Mat> images; //Store file data glob("E:/Desktop/Example/*.TIF", files, true); //Read all file paths that meet the requirements in the folder size_t num = files.size(); //Number of eligible files read cout << "read" << num << "images" << endl; for (int i = 0; i < num; i++) { cout << "The path to the "<< i + 1 << " file is:" << files[i] << endl; } for (int i = 0; i < num; i++) { Mat img = imread(files[i], IMREAD_GRAYSCALE); //read grayscale image if (img.empty()) { cerr << files[i] << " can't be loaded!" << endl; continue; } images.push_back(img); //Store image data in images } for (int i = 0; i < num; i++) { string name = format("%d", 1 + i); //display image imshow(name, images[i]); } waitKey(); return 0; }
The result is as follows: