要求:对文件夹中的所有图像批量读入,处理(进行直方图均衡化),保存到指定文件夹
所有图像保存在文件夹C:\Users\HanShuo\Desktop\人脸\yale排好的 中,要求批量进行直方图均衡处理,然后输出到文件夹C:\Users\HanShuo\Desktop\人脸\直方图均衡图像
具体操作如下:
一,利用cmd生产包含文件夹下所有图像名称的txt文档
1.在C:\Users\HanShuo\Desktop\人脸\yale排好的 的路径上输入cmd,回车
在命令提示行输入:dir/b>yaleok.txt
回车,会在文件夹下创造一个yaleok.txt文件,包含所有图片名称
二、编写代码如下:
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <fstream>
#include <iostream>
#include <windows.h>
#include <string>
using namespace cv;
using namespace std;
int main()
{
Mat srcImage, dstImage;
string image_name, savefile,imagepath;
int count = 1;
//读入yaleok.txt文件
ifstream inf("C:/Users/HanShuo/Desktop/人脸/yale排好的/yaleok.txt");
while (getline(inf, image_name))//从yalwb.txt中一行一行读取文件路径,放入IMAGE_NAME中
{
cout << "processing:" << image_name << endl;
//将读入的字符串与文件路径结合,得到文件路径字符串
imagepath = "C:/Users/HanShuo/Desktop/人脸/yale排好的/" + image_name;
//设置之后保存图像的路径与名字,这里采用与原来相同的图像名称,放在令一个文件夹下
savefile = "C:/Users/HanShuo/Desktop/人脸/直方图均衡图像/" + image_name;
//读入图像。注意这里一定是imread(imagepath,0),imread(imagepath)可能会在后续编译中出错
srcImage = imread(imagepath,0);
if (!srcImage.data) { printf("读取图片错误"); return false; }
//进行直方图均衡化
equalizeHist(srcImage, dstImage);
waitKey(0);
//count用于计算一共处理了多少图像
count++;
//将处理后的文件保存
imwrite(savefile, dstImage);
}
cout <<"一共处理的图像数目"<< count << endl;
waitKey(600000);
return 0;
}
由此完成。
三、运行结果
打开我们需要保存的文件夹,发现图像处理并保存成功。