普通的Threshold分割只是简单是或否的进行定值分割,很多时候需要分割的图像存在梯度效果,一刀切的效果很不理想;而opencv的adptiveThreshold则融合了考虑周边邻域的情况而进行的图像分割处理。另外做不做滤波处理等对图像分割影响也比较大。
1.adptiveThreshold分割,实验源码:
Mat img=imread("D:/ImageTest/sudoku.png",CV_LOAD_IMAGE_COLOR);
Mat dst1;
Mat dst2;
Mat dst3;
cv::cvtColor(img,img,COLOR_RGB2GRAY);//进行,灰度处理
medianBlur(img,img,5);//中值滤波
threshold(img,dst1, 127, 255, THRESH_BINARY);//阈值分割
adaptiveThreshold(img,dst2,255,ADAPTIVE_THRESH_MEAN_C,THRESH_BINARY,11,2);//自动阈值分割,邻域均值
adaptiveThreshold(img,dst3,255,ADAPTIVE_THRESH_GAUSSIAN_C,THRESH_BINARY,11,2);//自动阈值分割,高斯邻域
//ADAPTIVE_THRESH_MEAN_C : threshold value is the mean of neighbourhood area
//ADAPTIVE_THRESH_GAUSSIAN_C : threshold value is the weighted sum of neighbourhood values where weights are a gaussian window.
imshow("dst1", dst1);
imshow("dst2", dst2);
imshow("dst3", dst3);
imshow("img", img);
waitKey(0);
效果对比,很明显加入邻域权重后处理更理想:
2.加入滤波处理的最大类间方差分割
Mat img=imread("D:/ImageTest/pic2.png",CV_LOAD_IMAGE_COLOR);
Mat dst1;
Mat dst2;
Mat dst3;
cv::cvtColor(img,img,COLOR_RGB2GRAY);//进行,灰度处理
// medianBlur(img,img,5);
threshold(img,dst1, 127, 255, THRESH_BINARY);
threshold(img,dst2,0, 255, THRESH_OTSU);//最大类间方差法分割 Otsu algorithm to choose the optimal threshold value
Mat img2=img.clone();
GaussianBlur(img2,img2,Size(5,5),0);//高斯滤波去除小噪点
threshold(img2,dst3, 0, 255, THRESH_OTSU);
imshow("BINARY dst1", dst1);
imshow("OTSU dst2", dst2);
imshow("GaussianBlur OTSU dst3", dst3);
imshow("original img", img);
waitKey(0);
效果如下,显然不滤波和滤波差别明显: