基於OpenCV批量處理資料夾中的圖片的方法
阿新 • • 發佈:2019-01-25
在進行影象處理等問題是面臨的一個問題是如何批量的處理圖片,這些圖片存在在一個資料夾中,如何對這個資料夾中的資料進行批處理是非常重要的,下面介紹幾種常用的方法。
1. sprintf()函式法
這種方法最為簡單,他是將路徑的名字存放在一個數組中
//input為輸入資料夾的路徑,i為第幾幅影象
//影象的命名格式都是1.jpg,2.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[256];
char filename2[256];
for (int i = 1; i <= 10; 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(24, 24);
return 0;
}
2. windows中使用dir方法
在DOS的環境下將資料夾中的影象名稱生成一個txt文件,這樣就可以批量處理這個txt文件從而對影象進行批量處理。
命令形式為dir /b > example.txt
即輸出到example.txt檔案中。
//DOS環境下
C:\WINDOWS\system 32>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[256];
pipe = _popen(pCmd.c_str(), "rt");
if (pipe == NULL) {
cout << "file is not exist" << filename << endl;
exit(1);
}
while (!feof(pipe))
if (fgets(buf, 256, pipe) != NULL) {
output.push_back(string(buf));
output.back().resize(output.back().size() - 1); //將\n去掉
}
_pclose(pipe);
}
int main() {
vector<string>output; //output就是輸出的路徑集合
getDir("example", output);
for (auto c : output)
cout << c << endl;
}
輸出的結果如下,輸出了一系列的圖片名稱:
0_GaussianBlur.jpg
0_Perspective.jpg
0_Rotate108.jpg
0_Rotate144.jpg
0_Rotate180.jpg
0_Rotate216.jpg
0_Rotate252.jpg
0_Rotate288.jpg
0_Rotate324.jpg
0_Rotate36.jpg
0_Rotate360.jpg
0_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