class WatershedSegment{ private: cv::Mat markers; public: void setMarkers(const cv::Mat &image){ image.convertTo(markers,CV_32S); } cv::Mat process(const cv::Mat &image) { // Apply watershed cv::watershed(image,markers); markers.convertTo(markers,CV_8U); return markers; } }; int _tmain(int argc, _TCHAR* argv[]) { cv::Mat image = cv::imread("group.jpg"); cv::Mat binary = cv::imread("binary.bmp",0); //没加0害得我找好久错误的原因,即使"binary.bmp"为二值图像不加0读进来还是3通道 //cv::threshold(image,binary,60,255,CV_THRESH_BINARY); //阈值化操作 //binary = 255 - binary; //让前景变为白色区域 cv::namedWindow("binary",CV_WINDOW_AUTOSIZE); cv::imshow("binary",binary); cv::Mat fImage; cv::erode(binary,fImage,cv::Mat(),cv::Point(-1,-1),6); //binary = 255 - binary; //让前景变为白色区域//腐蚀去掉小的干扰物体得到前景图像 cv::namedWindow("eroded",CV_WINDOW_AUTOSIZE); cv::imshow("eroded",fImage); cv::Mat bImage; cv::dilate(binary,bImage,cv::Mat(),cv::Point(-1,-1),6); cv::threshold(bImage,bImage,1,128,cv::THRESH_BINARY_INV);//对原始二值图像阈值化并取反,得到背景图像 cv::namedWindow("bImage",CV_WINDOW_AUTOSIZE); cv::imshow("bImage",bImage); cv::Mat marker(binary.size(),CV_8U,cv::Scalar(0)); marker = fImage + bImage; //创建标记图像 cv::namedWindow("marker",CV_WINDOW_AUTOSIZE); cv::imshow("marker",marker); WatershedSegment segmenter; segmenter.setMarkers(marker); cv::Mat segment = segmenter.process(image); cv::namedWindow("segmenter",CV_WINDOW_AUTOSIZE); cv::imshow("segmenter",segment); cv::waitKey(0); return 0; }
opencv分水岭算法对图像进行分割,布布扣,bubuko.com
原文地址:http://blog.csdn.net/h_wlyfw/article/details/38564537