分水岭算法可以将图像中的边缘转化成“山脉,将均匀区域转换为”山谷“,这样有助于分隔目标。watershed(InputArray image,InputOutputArray markers)第一个参数是输入图像,需为8为三通道的彩色图像。第二个参数为函数调用后的输出结果,为32位单通道图像标记结果。
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace cv;
using namespace std;
int main()
{
Mat src,dst,canny_dst;
src = imread("1.jpg");
imshow( "原图" ,src);
cvtColor(src,dst,CV_RGB2GRAY);
Canny(dst,canny_dst,100,255);
//寻找轮廓
vector<vector<Point>>contours;
vector<Vec4i>hierarchy;
findContours(canny_dst,contours,hierarchy,CV_RETR_CCOMP,CV_CHAIN_APPROX_SIMPLE);
//分水岭算法第二个参数
Mat marks(src.size(),CV_32S);
marks=Scalar::all(0);
//绘制轮廓
for(int i=0;i < contours.size();i++)
{
Scalar color(rand()&255,rand()&255,rand()&255);
drawContours(marks,contours,i,color,2,8,hierarchy);
}
watershed(src,marks);
convertScaleAbs(marks,marks);
imshow("分水岭算法",marks);
waitKey();
return 0;
}