【OpenCV】批量读取图片

来源:互联网 发布:手机影视剪辑软件 编辑:程序博客网 时间:2024/05/19 16:36

在进行图片序列处理时,常常需要读取文件夹下的每一张图片,然后再进行分析处理,所以需要对文件名连续和无规则的情况分开进行讨论。

1.对于文件名连续的情况

在这种情况下,文件读取就容易的多,可以直接利用sprintf函数实现在窗口中连续读取统一文件夹下的图片序列,具体程序如下所示:

//实现从指定文件夹内读取规律命名的图片序列#include <stdio.h>#include <iostream>#include <opencv2\core\core.hpp>#include <opencv2\highgui\highgui.hpp>#include <opencv2\imgproc\imgproc.hpp>using namespace cv;using namespace std;int main(){//定义相关参数const int num = 100;char filename[50];char windowName[50];Mat srcImage;for (int i = 1; i <= num; i++){//sprintf读入制定路径下的图片序列sprintf(filename, "D\\test\\1(%d).jpg", i);sprintf(windowName, "NO%d", i);//按照文件名读取srcImage = imread(filename);if (!srcImage.data){cout << "读入图片有误!" << endl;return -1;}namedWindow(windowName);imshow(windowName, srcImage);cout << "NO" << i << endl;/*这里可以添加处理步骤*/}waitKey();return 0;}


2.对于文件名无规则

经过师兄的提醒,这种情况下可以直接使用OpenCV中的Directory类来进行实现,具体类定义如下:

class CV_EXPORTS Directory  {  public:      static std::vector<std::string> GetListFiles  ( const std::string& path, const std::string & exten = "*", bool addPath = true );      static std::vector<std::string> GetListFilesR ( const std::string& path, const std::string & exten = "*", bool addPath = true );      static std::vector<std::string> GetListFolders( const std::string& path, const std::string & exten = "*", bool addPath = true );  };  

具体用法如下:

需要注意的是,使用这个类时,应该加上contrib.hpp这个头文件

#include <iostream>  using namespace std;    #include <opencv2\opencv.hpp>  #include <opencv2\highgui\highgui.hpp>  #include <opencv2\contrib\contrib.hpp>  using namespace cv;    int main(int argc, char* argv[])  {      string dir_path = "D:\\opencv_pic\\test\\";      Directory dir;      vector<string> fileNames = dir.GetListFiles(dir_path, "*.jpg", false);        for(int i = 0; i < fileNames.size(); i++)      {          //get image name          string fileName = fileNames[i];          string fileFullName = dir_path + fileName;          cout<<"File name:"<<fileName<<endl;          cout<<"Full path:"<<fileFullName<<endl;            //load image          IplImage* srcImg = cvLoadImage(fileFullName.c_str(), -1);          cvShowImage("src", srcImg);          cvWaitKey(0);      }      return 0;  }  




0 0
原创粉丝点击