OpenCV-批量读取图像

时间:2023-01-20 09:34:49
在进行图像处理的过程中难免会用到批量图像读取,搜索了一些资料,实现了指定文件夹中图像的批量读取
#include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> #include <stdio.h> #include<windows.h>
using namespace std; using namespace cv; void readImgNamefromFile(char *fileName, vector<string>&imgNames) { //vector清零,参数设置 imgNames.clear(); WIN32_FIND_DATA file; int i = 0; char tempFilePath[MAX_PATH + 1]; char tempFileName[50]; //转换输入文件名 sprintf(tempFilePath, "%s/*", fileName); //-char转化为WCHAR WCHAR wszClassName[256]; memset(wszClassName, 0, sizeof(wszClassName)); MultiByteToWideChar(CP_ACP, 0, tempFilePath, strlen(tempFilePath) + 1, wszClassName,sizeof(wszClassName) / sizeof(wszClassName[0])); //查找待操作文件的相关属性,读取到WIN32_FIND_DATA HANDLE handle = FindFirstFile(wszClassName, &file); if (handle != INVALID_HANDLE_VALUE) { FindNextFile(handle, &file); FindNextFile(handle, &file); //循环遍历得到文件夹得所有文件名 do { sprintf(tempFileName, "%s", fileName); //--------------WCHAR转化为string wchar_t * wText = file.cFileName; DWORD dwNum = WideCharToMultiByte(CP_OEMCP, NULL, wText, -1, NULL, 0, NULL, FALSE);// WideCharToMultiByte的运用 char *psText; // psText为char*的临时数组,作为赋值给std::string的中间变量 psText = new char[dwNum]; WideCharToMultiByte(CP_OEMCP, NULL, wText, -1, psText, dwNum, NULL, FALSE);// WideCharToMultiByte的再次运用 imgNames.push_back(psText); delete[]psText;// psText的清除 imgNames[i].insert(0, tempFileName); i++; } while (FindNextFile(handle, &file)); } FindClose(handle); }

int main() { //设置读入图像文件夹得路径 char *fileName = "E:/图像数据/"; vector<string>imgNames; //获取对应文件夹下所有文件名 readImgNamefromFile(fileName, imgNames); //遍历对应文件夹下的所有文件名 for (int i = 0; i<imgNames.size(); i++) { Mat srcImage = imread(imgNames[i]); if( srcImage.empty()) { cout << "Couldn't load " << imgNames[i] << endl; continue; } namedWindow("Image", CV_WINDOW_NORMAL); imshow("Image", srcImage); waitKey(100); } //system("pause"); return 0; }

参考文献:
【1】寂寞的小乞丐http://www.cnblogs.com/wjy-lulu/p/6626405.html
【2】朱伟. OpenCV图像处理编程实例[M]. 电子工业出版社, 2016.