对灰度图像进行二值化,传入的图片是手写汉字的截图,通过二值化把字的部分提出来。用ostu进行二值化

#include <stdio.h>
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <stdio.h>
#include<stack>
using namespace std;
using namespace cv;
#include <fstream> #include <sys/uio.h>
#include <dirent.h> int main()
{ struct dirent *dirp;
DIR* dir = opendir("/Users/tanchao/Documents/c++work/myopencv5/myopencv5/image"); //int blockSize = 25;
//int constValue = 10;
while ((dirp = readdir(dir)) != nullptr)
{
if (dirp->d_type == DT_REG &&string(dirp->d_name)!=".DS_Store")//.DS_Store是Mac中隐藏文件,记录这个文件夹的属性,所以我们要跳过这个文件
{
Mat g_srcImage;
g_srcImage = imread("/Users/tanchao/Documents/c++work/myopencv5/myopencv5/image/"+string(dirp->d_name),);//第二个参数0表示灰度图读取
//imshow("test",g_srcImage);
Mat changeMat = Mat::zeros(cv::Size(g_srcImage.cols, g_srcImage.rows), CV_8UC1);//修改之后的图片
for(int i=;i<g_srcImage.rows;i++)
{
for(int j=;j<g_srcImage.cols;j++)
{ //if(int(g_srcImage.at<uchar>(i,j))>150)
//changeMat.ptr<uchar>(i)[j] = 255;
//else
//changeMat.ptr<uchar>(i)[j] = int(g_srcImage.at<uchar>(i,j));
//cout<<int(g_srcImage.at<uchar>(i,j))<<" ";
//adaptiveThreshold(g_srcImage, changeMat, 255, CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY_INV, blockSize, constValue); threshold(g_srcImage, changeMat, , , CV_THRESH_OTSU); }
//cout << "\n"<<endl;
}
cout<<"/Users/tanchao/Documents/c++work/myopencv5/myopencv5/change/"+string(dirp->d_name)<<endl;
imwrite("/Users/tanchao/Documents/c++work/myopencv5/myopencv5/quanjuyuzhi/"+string(dirp->d_name),changeMat);//加了用来截图
}
}
closedir(dir);
waitKey();
return ; }

Mac中opencv批量对图片进行二值化-LMLPHP

其实也可以用自适应二值化和自己设定阈值进行二值化,具体的可以根据代码中注释部分进行修改。

05-11 17:13