1 #include <opencv2/opencv.hpp>
2 #include <iostream>
3
4 using namespace cv;
5 using namespace std;
6
7 Mat watershedCluster(Mat &image, int &numSegments);
8 //参数分别为分割后图像,分割块数,输入原图
9 void createDisplaySegments(Mat &segments, int numSegments, Mat &image);
10 int main(int argc, char** argv) {
11 Mat src = imread("cvtest.png");
12 if (src.empty()) {
13 printf("could not load image...\n");
14 return -1;
15 }
16 namedWindow("input image", CV_WINDOW_AUTOSIZE);
17 imshow("input image", src);
18
19 int numSegments;
20 Mat markers = watershedCluster(src, numSegments);
21 createDisplaySegments(markers, numSegments, src);
22 waitKey(0);
23 return 0;
24 }
25
26 Mat watershedCluster(Mat &image, int &numComp) {
27 // 二值化
28 Mat gray, binary;
29 cvtColor(image, gray, COLOR_BGR2GRAY);
30 threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);
31 // 形态学与距离变换
32 Mat k = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
33 morphologyEx(binary, binary, MORPH_OPEN, k, Point(-1, -1));
34 Mat dist;
35 distanceTransform(binary, dist, DistanceTypes::DIST_L2, 3, CV_32F);
36 normalize(dist, dist, 0.0, 1.0, NORM_MINMAX);
37
38 // 开始生成标记
39 threshold(dist, dist, 0.1, 1.0, THRESH_BINARY);
40 normalize(dist, dist, 0, 255, NORM_MINMAX);
41 dist.convertTo(dist, CV_8UC1);
42
43 // 标记开始
44 vector<vector<Point>> contours;
45 vector<Vec4i> hireachy;
46 findContours(dist, contours, hireachy, RETR_CCOMP, CHAIN_APPROX_SIMPLE);
47 if (contours.empty()) {
48 return Mat();
49 }
50
51 Mat markers(dist.size(), CV_32S);
52 markers = Scalar::all(0);
53 for (int i = 0; i < contours.size(); i++) {
54 drawContours(markers, contours, i, Scalar(i + 1), -1, 8, hireachy, INT_MAX);
55 }
56 circle(markers, Point(5, 5), 3, Scalar(255), -1);
57
58 // 分水岭变换
59 watershed(image, markers);
60 numComp = contours.size();
61 return markers;
62 }
63
64 void createDisplaySegments(Mat &markers, int numSegments, Mat &image) {
65 // generate random color
66 vector<Vec3b> colors;
67 for (size_t i = 0; i < numSegments; i++) {
68 int r = theRNG().uniform(0, 255);
69 int g = theRNG().uniform(0, 255);
70 int b = theRNG().uniform(0, 255);
71 colors.push_back(Vec3b((uchar)b, (uchar)g, (uchar)r));
72 }
73
74 // 颜色填充与最终显示
75 Mat dst = Mat::zeros(markers.size(), CV_8UC3);
76 int index = 0;
77 for (int row = 0; row < markers.rows; row++) {
78 for (int col = 0; col < markers.cols; col++) {
79 index = markers.at<int>(row, col);
80 if (index > 0 && index <= numSegments) {
81 dst.at<Vec3b>(row, col) = colors[index - 1];
82 }
83 else {
84 dst.at<Vec3b>(row, col) = Vec3b(255, 255, 255);
85 }
86 }
87 }
88 imshow("分水岭图像分割-演示",dst);
89 return;
90 }