#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
Mat watershedCluster(Mat& image, int& Num_contours);
void createDisplaySegments(Mat& markers,int Num_contours,Mat& image);
int main(int argc, char** argv)
{
Mat src;
src = imread("../path.jpg");
if (src.empty())
{
cout << "could not load image1..." << endl;
return -1;
}
namedWindow("src", WINDOW_AUTOSIZE);
imshow("src", src);
int Num_contours;
Mat markers = watershedCluster(src, Num_contours);
cout << "有 " << Num_contours << " 个轮廓"<< endl;
createDisplaySegments(markers, Num_contours, src);
waitKey(0);
return 0;
}
Mat watershedCluster(Mat& image, int& num_contours)
{
Mat means;
pyrMeanShiftFiltering(image, means, 21, 51);
Mat gray, temp_threshold;
cvtColor(means, gray, COLOR_BGR2GRAY);//转换为灰度
threshold(gray, temp_threshold, 0, 255, THRESH_BINARY | THRESH_OTSU);//二值化
//形态学操作
Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
morphologyEx(temp_threshold, temp_threshold, MORPH_OPEN, kernel, Point(-1, -1));
Mat temp_distance;
//距离变换
distanceTransform(temp_threshold, temp_distance, DistanceTypes::DIST_L2, 3, CV_32F);
normalize(temp_distance, temp_distance, 0.0, 1.0, NORM_MINMAX);
//使用阈值,再次二值化,得到标记
threshold(temp_distance, temp_distance, 0.4, 1.0, THRESH_BINARY);
normalize(temp_distance, temp_distance, 0, 255, NORM_MINMAX);
temp_distance.convertTo(temp_distance, CV_8UC1);
//开始标记,查找轮廓
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(temp_distance, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point());
if (contours.empty())//如果没有找到,则返回
{
return Mat();
}
Mat makers_temp_contours = Mat::zeros(image.size(), CV_32S);//定义标志Mat
for (int i = 0; i < contours.size(); i++)
{
drawContours(makers_temp_contours, contours, i, Scalar(i + 1), -1, 8, hierarchy, INT_MAX);
}
circle(makers_temp_contours, Point(5, 5), 3, Scalar(255), -1);
//分水岭变换
watershed(image, makers_temp_contours);
//Mat mark = Mat::zeros(makers_temp_contours.size(), CV_8UC1);
//makers_temp_contours.convertTo(mark, CV_8UC1);//数据类型转换
//bitwise_not(mark, mark, Mat());//取反//让每个区域显灰白
num_contours = contours.size();//多少个轮廓
//imshow("Cluster", mark);
return makers_temp_contours;
}
void createDisplaySegments(Mat& markers, int Num_contours, Mat& image)
{
//对每个分割区域着色输出结果
vector<Vec3b> colors;
for (size_t i = 0; i < Num_contours; i++) {
int r = theRNG().uniform(0, 255);
int g = theRNG().uniform(0, 255);
int b = theRNG().uniform(0, 255);
colors.push_back(Vec3b((uchar)b, (uchar)g, (uchar)r));
}
Mat dst = Mat::zeros(markers.size(), CV_8UC3);
for (int row = 0; row < markers.rows; row++)
{
for (int col = 0; col < markers.cols; col++)
{
int index = markers.at<int>(row, col);
if (index > 0 && index <= Num_contours)
{
dst.at<Vec3b>(row, col) = colors[index - 1];
}
else
{
dst.at<Vec3b>(row, col) = Vec3b(255,255,255);
}
}
}
imshow("Final Image", dst);
return;
}
输出结果: