/**
Created by kaijun on 10/17/19.
图像分水岭
*/
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
string path = "/home/kaijun/Pictures/wan.png";
Mat src = imread(path,IMREAD_COLOR);
int n=1;
void onMouse(int event, int x, int y, int flags, void* userdata){
Mat markers = *(Mat*)userdata;
// 当鼠标左键按下的时候
if(event == EVENT_LBUTTONDOWN){
circle(markers,Point(x,y),50,Scalar(n++),-1);
imshow("markers",markers);
}
// 当鼠标右键按下的时候
if(event == EVENT_RBUTTONDOWN){
// 颜色列表
vector<Vec3b> colors={Vec3b(255,255,0),Vec3b(0,255,255)};
// 执行分水岭操作
watershed(src,markers);
// 定义一个用于显示结果的图像
Mat result(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<n){
result.at<Vec3b>(row,col) = colors[index-1];
cout<<index<<n<<endl;
}
}
}
imshow("result",result);
}
}
int main(int argc,char** argv){
// 显示原图像
imshow("src",src);
// 彩色图像转成灰度图像
Mat gray;
cvtColor(src,gray,COLOR_BGR2GRAY);
imshow("gray",gray);
// 定义用于记录标记的图像
Mat markers(src.size(),CV_32S);
// 注册鼠标滑动时间
setMouseCallback("gray",onMouse,&markers);
Mat binary;
threshold(gray,binary,0,255,THRESH_BINARY|THRESH_TRIANGLE);
imshow("binary",binary);
waitKey(0);
return 0;
}