1.Python
主要是利用glob模块。glob是python自己带的一个文件操作相关模块,内容不多,可以用它查找符合自己目的的文件。
# encoding: UTF-8
import glob as gb
import cv2
#Returns a list of all folders with participant numbers
img_path = gb.glob("numbers\\*.jpg")
for path in img_path:
img = cv2.imread(path)
cv2.imshow('img',img)
cv2.waitKey(1000)
2.C++ and OpenCV
OpenCV自带一个函数glob()可以遍历文件,如果用这个函数的话,遍历文件也是非常简单的。
#include<opencv2\opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
vector<Mat> read_images_in_folder(cv::String pattern);
int main()
{
cv::String pattern = "G:/temp_picture/*.jpg";
vector<Mat> images = read_images_in_folder(pattern);
return 0;
}
vector<Mat> read_images_in_folder(cv::String pattern)
{
vector<cv::String> fn;
glob(pattern, fn, false);
vector<Mat> images;
size_t count = fn.size(); //number of png files in images folder
for (size_t i = 0; i < count; i++)
{
images.push_back(imread(fn[i]));
imshow("img", imread(fn[i]));
waitKey(1000);
}
return images;
}
3.C++
int main(int argc, char **argv)
{
if (argc != 2)
{
std::cout << "Usage: images file path error" << std::endl;
}
struct _finddata_t file;
intptr_t If;
std::string path,tempPath; //遍历文件夹中的所有图片
path = path.assign(argv[1]); //文件的路径
tempPath = path.assign(argv[1]);
if ((If = _findfirst(path.append("\\*").c_str(), &file)) == -1) //不加*也会报错
{
std::cout << "Not find image file" << std::endl;
}
else
{
while (_findnext(If, &file) == 0)
{
std::cout << "file name: " << path.substr(0, path.length() - 1) << file.name << std::endl;
cv::Mat srcImage = cv::imread(tempPath + "\\" + file.name, 0);//第一个图片路径..是打不开的
if (!srcImage.data)
{
printf("picture read error");
continue;
}
cv::Mat vecImage(srcImage.rows, srcImage.cols, CV_8UC3, cv::Scalar::all(0));
/*
对图像进行处理操作
*/
std::string resFiles = "resluts/"; //将矢量化图片保存在reslut文件中
cv::imwrite(resFiles + file.name, vecImage); // 遍历所有图片并写出
}
}
_findclose(If);
system("PAUSE");
return 0;
}
4.C++ and Boost
用到了Boost库中的filesystem
#include <boost/filesystem.hpp>
#include<iostream>
#include<opencv2\opencv.hpp>
using namespace cv;
using namespace std;
using namespace boost::filesystem;
void readFilenamesBoost(vector<string> &filenames, const string &folder);
int main()
{
string folder = "G:/temp_picture/";
vector<string> filenames;
readFilenamesBoost(filenames, folder);
for (size_t i = 0; i < filenames.size(); ++i)
{
Mat src = imread(folder + filenames[i]);
if (!src.data)
cerr << "Problem loading image!!!" << endl;
imshow("img", src);
waitKey(1000);
}
return 0;
}
void readFilenamesBoost(vector<string> &filenames, const string &folder)
{
path directory(folder);
directory_iterator itr(directory), end_itr;
string current_file = itr->path().string();
for (; itr != end_itr; ++itr)
{
if (is_regular_file(itr->path()))
{
string filename = itr->path().filename().string(); // returns just filename
filenames.push_back(filename);
}
}
}