处理方法
1、二值分割(整体threshold只有一个阈值)
2、形态学处理
3、距离变换
4、阈值化二值分割(局部AdaptiveThreshold每个区域都有一个阈值)
5、连通区域计数
原图
代码
# include<opencv2\opencv.hpp>
# include <iostream>
# include <math.h>
using namespace std;
using namespace cv;
int main(int argc, char** argv) {
Mat src, dst,gray_src,binary;
src = imread("E:/tuku/case005.png");
if (src.empty()) {
cout << "can't find this picture...";
return -1;
}
imshow("input", src);
cvtColor(src, gray_src, COLOR_BGR2GRAY);
//照片不够清楚 所以加了一个掩模操作
//必要的时候还可以加入拉普拉多算子增强边缘
Mat kernel1 = (Mat_<char>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);
filter2D(gray_src, gray_src, gray_src.depth(), kernel1);
//二值分割
threshold(gray_src, binary, 0, 255, THRESH_BINARY | THRESH_TRIANGLE); //颜色单一时,使用THRESH_TRIANGLE比OTSU好
imshow("binary image", binary);
//形态学操作
Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
dilate(binary, binary, kernel);
imshow("dilate image", binary);
//距离变换
Mat dist;
bitwise_not(binary, binary);//取反
distanceTransform(binary, dist, DIST_L2, 3);//(点到零像素点的距离)
normalize(dist, dist, 0, 1.0, NORM_MINMAX);
imshow("dist image", dist);
//阈值化二值分割
Mat dist_8u;
dist.convertTo(dist_8u, CV_8U);
adaptiveThreshold(dist_8u, dist_8u, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 85, 0.0);//使用这个比threshold效果好,
//腐蚀,使断开的区域连通
kernel = getStructuringElement(MORPH_RECT, Size(7, 7), Point(-1, -1));//Size的大小可以自己调试一下
dilate(dist_8u, dist_8u, kernel,Point(-1,-1),2);
imshow("dist_8u image", dist_8u);
//连通区域计数
vector<vector<Point>>contours;
findContours(dist_8u, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
//draw reslut
Mat markers = Mat::zeros(src.size(), CV_8UC3);
RNG rng(12345);
for (size_t t = 0; t < contours.size(); t++) {
drawContours(markers, contours, t, Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)), -1,
8, Mat());
}
printf("number of corners:%d\n", contours.size());
imshow("Final results", markers);
waitKey(0);
return 0;
}