@@ -11,6 +11,11 @@ using std::endl;
11
11
cv::Mat img_preview;
12
12
cv::Mat img;
13
13
cv::Mat markers;
14
+ cv::Mat drawRect;
15
+ int x_0 = -1 ;
16
+ int y_0 = -1 ;
17
+ int x_1, y_1;
18
+ int drawr = 0 ;
14
19
15
20
bool finished;
16
21
@@ -34,33 +39,60 @@ static void onMouseClick(int event, int x, int y, int, void*) {
34
39
return ;
35
40
}
36
41
37
- if (event == cv::EVENT_LBUTTONDOWN) {
38
- cv::ellipse (markers, cv::Point (x, y), cv::Size (1 , 1 ),
42
+ if (event == cv::EVENT_LBUTTONDOWN && drawr == 0 ) {
43
+ if (x_0 < 0 ) {
44
+ x_0 = x;
45
+ y_0 = y;
46
+ cv::ellipse (markers, cv::Point (x, y), cv::Size (1 , 1 ),
39
47
0 , 0 , 360 , cv::GC_FGD, 3 );
40
- cv::ellipse (img_preview , cv::Point (x, y), cv::Size (1 , 1 ),
48
+ cv::ellipse (drawRect , cv::Point (x, y), cv::Size (1 , 1 ),
41
49
0 , 0 , 360 , cv::Scalar (0 , 0 , 255 ), 3 );
50
+ drawr = 1 ;
51
+ }
52
+
53
+ cv::addWeighted (img,0.7 ,drawRect,0.3 , 0 , img_preview);
54
+
42
55
cv::imshow (" image" , img_preview);
43
56
return ;
44
57
}
45
-
46
- if (event == cv::EVENT_RBUTTONDOWN) {
58
+ if ( event == cv::EVENT_LBUTTONUP) {
59
+ drawr = 2 ;
60
+ }
61
+ if (drawr == 1 ) { // Just moving
62
+ drawRect.setTo (0 );
63
+ cv::rectangle (drawRect, cv::Point (x_0,y_0), cv::Point (x,y), cv::Scalar (0 ,0 ,255 ), -1 );
64
+
65
+ cv::addWeighted (img,0.7 ,drawRect,0.3 , 0 , img_preview);
66
+ x_1 = x; y_1 = y;
67
+ cv::imshow (" image" , img_preview);
68
+ return ;
69
+ }
70
+
71
+ if (drawr == 2 ) {
47
72
cv::Mat bg;
48
73
cv::Mat fg;
74
+ cv::rectangle (markers, cv::Point (x_0,y_0), cv::Point (x_1,y_1), cv::GC_PR_FGD, -1 );
49
75
cv::grabCut (img, markers, cv::Rect (0 , 0 , img.cols - 1 , img.rows - 1 ),
50
76
bg, fg, 5 , cv::GC_EVAL);
51
77
displayResult ();
52
78
return ;
53
79
}
54
80
}
55
81
56
- int main (int argc, char ** argv) {
57
- if (argc != 2 ) {
82
+ void help (char ** argv) {
58
83
cout << " \n Example 12-3. Using GrabCut for background removal"
59
- << " \n - Use left click on the image to select foreground point "
60
- << " \n - Use right clock on the image to perform GrabCut"
84
+ << " \n - Use left mouse to drag a rectangle over the object "
85
+ << " \n - On release of left mouse button, we will perform GrabCut"
61
86
<< " \n - Press any key to terminate program"
62
87
<< " \n Usage: "
63
- << argv[0 ] << " <path/imagename>\n " << endl;
88
+ << argv[0 ] << " <path/imagename>\n "
89
+ << " \n Example:\n " << argv[0 ] << " ../stuff.jpg\n " << endl;
90
+ }
91
+
92
+
93
+ int main (int argc, char ** argv) {
94
+ help (argv);
95
+ if (argc != 2 ) {
64
96
return -1 ;
65
97
}
66
98
@@ -74,6 +106,7 @@ int main(int argc, char** argv) {
74
106
markers.setTo (cv::GC_PR_BGD);
75
107
76
108
img_preview = img.clone ();
109
+ drawRect = img.clone ();
77
110
78
111
finished = false ;
79
112
0 commit comments