天天看點

基于OpenCV批量處理檔案夾中的圖檔的方法

在進行圖像處理等問題是面臨的一個問題是如何批量的處理圖檔,這些圖檔存在在一個檔案夾中,如何對這個檔案夾中的資料進行批處理是非常重要的,下面介紹幾種常用的方法。

1. sprintf()函數法

這種方法最為簡單,他是将路徑的名字存放在一個數組中

//input為輸入檔案夾的路徑,i為第幾幅圖像
//圖像的命名格式都是jpg,jpg,...
sprintf(filename, "%s\\%d.jpg", input, i)
           

示例:

#include<opencv2/opencv.hpp>  
#include<iostream>   
using namespace std;
using namespace cv;

void Resize(int m, int n) {
    char filename[];
    char filename2[];
    for (int i = ; i <= ; i++) {
        //input中有10個檔案
        sprintf(filename,"%s\\%d.jpg","input",i); 
        Mat img = imread(filename);
        //  imshow("img", img);
        Mat res;
        resize(img, res, Size(m, n));
        //輸出
        sprintf(filename2, "%s\\%d_resize.jpg","output",i);
        imwrite(filename2, res);
    }
}
int main() {
    Resize(, );
    return ;
}
           

2. windows中使用dir方法

在DOS的環境下将檔案夾中的圖像名稱生成一個txt文檔,這樣就可以批量處理這個txt文檔進而對圖像進行批量處理。

指令形式為

dir /b > example.txt

即輸出到example.txt檔案中。

//DOS環境下
C:\WINDOWS\system32>cd C:\Users\AAA\Desktop\example
C:\Users\AAA\Desktop\example>dir /b > example.txt
           

3. c/c++中調用cmd的dir方法

這種方法要比上面的方法要好用的多,因為不必來回折騰,而且非常的友善。

代碼如下:

需要注意這一行語句,就是将字元串的最後一個\n去掉,可以單步調式去觀察。

output.back().resize(output.back().size() - 1);

#include<iostream>
#include<string>
#include<vector>
using namespace std;
void getDir(string filename, vector<string> &output){
    FILE* pipe = NULL;
    string pCmd = "dir /B " + filename;
    char buf[];
    pipe = _popen(pCmd.c_str(), "rt");
    if (pipe == NULL) {
        cout << "file is not exist" << filename << endl;
        exit();
    }
    while (!feof(pipe))
        if (fgets(buf, , pipe) != NULL) {
            output.push_back(string(buf));
            output.back().resize(output.back().size() - );  //将\n去掉
        }
    _pclose(pipe);
}
int main() {
    vector<string>output;   //output就是輸出的路徑集合
    getDir("example", output);
    for (auto c : output)
        cout << c << endl;
}
           

輸出的結果如下,輸出了一系列的圖檔名稱:

_GaussianBlur.jpg
_Perspective.jpg
_Rotate108.jpg
_Rotate144.jpg
_Rotate180.jpg
_Rotate216.jpg
_Rotate252.jpg
_Rotate288.jpg
_Rotate324.jpg
_Rotate36.jpg
_Rotate360.jpg
_Rotate72.jpg
example.txt
IMG_20151003_17250_GaussianBlur.jpg
IMG_20151003_17250_Perspective.jpg
IMG_20151003_17250_Rotate108.jpg
IMG_20151003_17250_Rotate144.jpg
IMG_20151003_17250_Rotate180.jpg
IMG_20151003_17250_Rotate216.jpg
IMG_20151003_17250_Rotate252.jpg
IMG_20151003_17250_Rotate288.jpg
IMG_20151003_17250_Rotate324.jpg
IMG_20151003_17250_Rotate36.jpg
IMG_20151003_17250_Rotate360.jpg
           

4.OpenCV的類方法

OpenCV中有實作周遊檔案夾下所有檔案的類Directory,它裡面包括3個成員函數:

(1)、GetListFiles:周遊指定檔案夾下的所有檔案,不包括指定檔案夾内的檔案夾;

(2)、GetListFolders:周遊指定檔案夾下的所有檔案夾,不包括指定檔案夾下的檔案;

(3)、GetListFilesR:周遊指定檔案夾下的所有檔案,包括指定檔案夾内的檔案夾。

若要使用Directory類,則需包含contrib.hpp頭檔案,此類的實作在contrib子產品。

注意:OpenCV3中沒有這個子產品,因為安全性移除了,可以安裝,此種方法具體可見:

http://blog.csdn.net/fengbingchun/article/details/42435901