1. 程式人生 > >Opencv批量處理圖片的兩種方法

Opencv批量處理圖片的兩種方法

轉自:http://blog.csdn.net/hei_ya/article/details/51387624

在生成訓練集的時通常需要對資料夾中圖片進行批處理,本文簡要介紹影象批量讀取、處理、儲存的方法。


方法一:

1.生成圖片描述檔案

    對於有多幅影象的資料夾,首先生成txt檔案,儲存圖片路徑。


   在DOS模式下匯入資料夾路徑並生成TXT檔案:



2.通過TXT批量處理圖片

<span style="font-size:18px;">#include<opencv2/opencv.hpp>
#include<iostream>
#include<time.h>
#include<fstream>

using namespace std;
using namespace cv;

void main()
{
	ifstream file("C:/Users/Administrator/Desktop/date/MIT/MIT人臉庫/faces/face.txt");

	int img_index = 0;

	while (!file.eof())
	{
		char txt_cont[200];
		file.getline(txt_cont,200);

		char img_file[200],save_file[200];

		sprintf(img_file, "C:/Users/Administrator/Desktop/date/MIT/MIT人臉庫/faces/%s", txt_cont);
		sprintf(save_file, "C:/Users/Administrator/Desktop/date/MIT/MIT人臉庫/save/%d.jpg", img_index);

		Mat src = imread(img_file);

		img_index++;
		
		imwrite(save_file,src);
	}
	
}</span>

方法二:

利用Directory類實現資料夾中特定格式影象的遍歷,Directory的標頭檔案是windows.h。

#include<opencv2/opencv.hpp>
#include<iostream>
#include<vector>
#include<string>
#include <windows.h>

using namespace std;
using namespace cv;


void main()
{
	Directory dir;

	string path1 = "C:\\Users\\Administrator\\Desktop\\date\\MIT\\MIT人臉庫\\faces";
	string  exten1 = "*.bmp";

	vector<string> filenames = dir.GetListFiles(path1, exten1, false);

	int size = filenames.size();

	for (int i = 0; i < size;i++)
	{
		cout << filenames[i] << endl;
	}
}

2. 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(), CV_LOAD_IMAGE_UNCHANGED);  
        cvShowImage("src", srcImg);  
        cvWaitKey(0);  
    }  
    return 0;  
}  
參考: http://blog.csdn.net/qq_34784753/article/details/68935628