实例8:opencv批量阈值分割JPG图像并显示保存
#include <iostream>
#include <io.h> // 当中含有_finddata_t
#include <string>
#include <vector>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#define NUMBER 80 //(JPG文件数量为NUMBER-1)
using namespace std;
using namespace cv;
void Threshold_Demo(vector<Mat> imag)
{
char ad[128] = { 0 };
Mat gray_src,dst;
const char* output_title = "binary image";//定义输出标题为二进制图像
for(int i=0;i<imag.size();i++)//
{
cvtColor(imag[i], gray_src, CV_BGR2GRAY);//RGB图像对象src转换为灰度图像对象gray_src
//imshow("GRAY", gray_src);//显示灰度图像
threshold(gray_src, dst, 178, 255, THRESH_BINARY);//对gray_src阈值分割,阈值设置为178
//保存阈值分割后图像
sprintf_s(ad, "F:\\Software\\VTK8.2.0\\vtk1\\helloVtk\\JPG_threshold\\threshold_%d.jpg", i+1);
imwrite(ad, dst);
namedWindow(output_title, CV_WINDOW_AUTOSIZE);
imshow(output_title, dst);
waitKey();//键盘任意键关闭
}
}
int main()
{
vector<Mat> images;
for (int a = 1; a < NUMBER;a+=10) // a <=Count would do one too many...
{
string filename = format("F:\\Software\\VTK8.2.0\\vtk1\\helloVtk\\JPG_images\\%d.jpg", a);//JPG文件的存储路径
Mat img = imread(filename); //读取图像
if (img.empty()) // 如果图像为空
{
cerr << "whaa " << filename << " can't be loaded!" << endl;
continue;
}
images.push_back(img);//图像保存进容器
}
//进行批量阈值分割与保存
Threshold_Demo(images);
return 0;
}
原图像和阈值设定阈值分割后的图像:
阈值分割后保存图像: