First look at the effect
DescriptionUsing the watershed algorithm to cut the image, set a marker image to achieve a better effect, but also to prevent excessive cutting.
1, first of all, the threshold value of the two-value image corrosion, remove the small white area, the image of the foreground area. and the foreground region with 255 white Mark 2, the same to the threshold of the image expansion, and then the threshold and reverse. Get the background area.
and a 128 grayscale representation of 3, the foreground and background superimposed together in the same image display. 4, using the mark chart and the original picture, using OpenCV watershed to cut the image. Source Code
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 watershedcv::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) ; No, plus 0, I've been looking for a long time wrong reason. Even if "binary.bmp" is a two value image without 0 read in or 3 channel//cv::threshold (image,binary,60,255,cv_thresh_binary); Threshold operation//binary = 255-binary; Make the foreground into white area cv::namedwindow ("binary", cv_window_autosize); Cv::imshow ("binary", binary); Cv::mat Fimage;cv::erode ( Binary,fimage,cv::mat (), CV::P oint ( -1,-1), 6); binary = 255-binary; Make the foreground into white area//corrosion Remove small interfering object to get foreground image Cv::namedwindow ("eroded", cv_window_autosize); Cv::imshow ("eroded", fimage); Cv::mat BIMAGE;CV::d ilate (Binary,bimage,cv::mat (), CV::P oint ( -1,-1), 6); Cv::threshold (Bimage,bimage,1,128,cv::thresh_ BINARY_INV);//to the original binary image thresholding and inversion, get the background image Cv::namedwindow ("Bimage", Cv_window_autosizE); Cv::imshow ("Bimage", bimage); Cv::mat marker (Binary.size (), Cv_8u,cv::scalar (0)); marker = Fimage + bimage; Create Tagged Image 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 watershed algorithm for cutting images