1
2
3
4
5
6
7
8
|
cv::Mat image=cv::imread(
"D:\\opencvStudy\\pic\\watersheds.jpg"
);
if
(!image.data)
std::cout<<
"Error loading the picture"
<<std::endl;
//convert to binary image,
cv::Mat binary ;
cv::cvtColor(image,binary,CV_BGR2GRAY);
cv::threshold(binary,binary,100,255,THRESH_BINARY);
|
1
2
3
4
5
6
7
|
cv::Mat fg;
//foreground
cv::erode(binary,fg,cv::Mat(),cv::Point(-1,-1),2);
//idenify image pixeles without objects
cv::Mat bg;
//background
cv::dilate(binary,bg,cv::Mat(),cv::Point(-1,-1),3);
cv::threshold(bg,bg,1,128,cv::THRESH_BINARY_INV);
|
1
2
3
4
|
//create markers image
cv::Mat markers(binary.size(),CV_8U,cv::Scalar(0));
markers=bg+fg;
cv::imshow(
"markers"
,markers);
|
1
2
3
4
|
//create watershed segmentation object
WatershedSegment segmenter;
segmenter.setMarkers(markers);
cv::Mat result=segmenter.process(image);
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
// CookBook-Chapter 5:Segmenting images using watersheds
// By Steven 2012.11.7
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
using
namespace
cv;
using
namespace
std;
class
WatershedSegment{
private
:
cv::Mat markers;
public
:
void
setMarkers(cv::Mat &markerImage)
{
markerImage.convertTo(markers,CV_32S);
//convert to image of ints
}
cv::Mat process(cv::Mat &image)
{
cv::watershed(image,markers);
markers.convertTo(markers,CV_8U);
return
markers;
}
};
int
main()
{
cv::Mat image=cv::imread(
"D:\\opencvStudy\\pic\\watersheds.jpg"
);
if
(!image.data)
std::cout<<
"Error loading the picture"
<<std::endl;
//convert to binary image,
cv::Mat binary ;
cv::cvtColor(image,binary,CV_BGR2GRAY);
cv::threshold(binary,binary,100,255,THRESH_BINARY);
//display them
cv::imshow(
"OriginalImage"
,image);
cv::imshow(
"OriginalBinary"
,binary);
//obviously,in the binaryImage,there is so much noise around the object;
//so next is to eliminate noise and smaller objects
cv::Mat fg;
//foreground
cv::erode(binary,fg,cv::Mat(),cv::Point(-1,-1),2);
cv::imshow(
"fg"
,fg);
//idenify image pixeles without objects
cv::Mat bg;
//background
cv::dilate(binary,bg,cv::Mat(),cv::Point(-1,-1),3);
cv::threshold(bg,bg,1,128,cv::THRESH_BINARY_INV);
cv::imshow(
"bg"
,bg);
//create markers image
cv::Mat markers(binary.size(),CV_8U,cv::Scalar(0));
markers=bg+fg;
cv::imshow(
"markers"
,markers);
//create watershed segmentation object
WatershedSegment segmenter;
segmenter.setMarkers(markers);
cv::Mat result=segmenter.process(image);
cv::threshold(result,result,0,255,cv::THRESH_BINARY);
//result=result&1;
imshow(
"final_result"
,result);
waitKey(0);
return
0;
}
|