1 /**
2 * @file BackProject_Demo2.cpp
3 * @brief Sample code for backproject function usage ( a bit more elaborated )
4 * @author OpenCV team
5 */
6
7 #include "opencv2/imgproc/imgproc.hpp"
8 #include "opencv2/imgcodecs.hpp"
9 #include "opencv2/highgui/highgui.hpp"
10
11 #include <iostream>
12
13 using namespace cv;
14 using namespace std;
15
16 /// Global Variables
17 Mat src; Mat hsv;
18 Mat mask;
19
20 int lo = 20; int up = 20;
21 const char* window_image = "Source image";
22
23 /// Function Headers
24 void Hist_and_Backproj( );
25 void pickPoint (int event, int x, int y, int, void* );
26
27 /**
28 * @function main
29 */
main(int,char ** argv)30 int main( int, char** argv )
31 {
32 /// Read the image
33 src = imread( argv[1], 1 );
34 /// Transform it to HSV
35 cvtColor( src, hsv, COLOR_BGR2HSV );
36
37 /// Show the image
38 namedWindow( window_image, WINDOW_AUTOSIZE );
39 imshow( window_image, src );
40
41 /// Set Trackbars for floodfill thresholds
42 createTrackbar( "Low thresh", window_image, &lo, 255, 0 );
43 createTrackbar( "High thresh", window_image, &up, 255, 0 );
44 /// Set a Mouse Callback
45 setMouseCallback( window_image, pickPoint, 0 );
46
47 waitKey(0);
48 return 0;
49 }
50
51 /**
52 * @function pickPoint
53 */
pickPoint(int event,int x,int y,int,void *)54 void pickPoint (int event, int x, int y, int, void* )
55 {
56 if( event != EVENT_LBUTTONDOWN )
57 { return; }
58
59 // Fill and get the mask
60 Point seed = Point( x, y );
61
62 int newMaskVal = 255;
63 Scalar newVal = Scalar( 120, 120, 120 );
64
65 int connectivity = 8;
66 int flags = connectivity + (newMaskVal << 8 ) + FLOODFILL_FIXED_RANGE + FLOODFILL_MASK_ONLY;
67
68 Mat mask2 = Mat::zeros( src.rows + 2, src.cols + 2, CV_8UC1 );
69 floodFill( src, mask2, seed, newVal, 0, Scalar( lo, lo, lo ), Scalar( up, up, up), flags );
70 mask = mask2( Range( 1, mask2.rows - 1 ), Range( 1, mask2.cols - 1 ) );
71
72 imshow( "Mask", mask );
73
74 Hist_and_Backproj( );
75 }
76
77 /**
78 * @function Hist_and_Backproj
79 */
Hist_and_Backproj()80 void Hist_and_Backproj( )
81 {
82 MatND hist;
83 int h_bins = 30; int s_bins = 32;
84 int histSize[] = { h_bins, s_bins };
85
86 float h_range[] = { 0, 179 };
87 float s_range[] = { 0, 255 };
88 const float* ranges[] = { h_range, s_range };
89
90 int channels[] = { 0, 1 };
91
92 /// Get the Histogram and normalize it
93 calcHist( &hsv, 1, channels, mask, hist, 2, histSize, ranges, true, false );
94
95 normalize( hist, hist, 0, 255, NORM_MINMAX, -1, Mat() );
96
97 /// Get Backprojection
98 MatND backproj;
99 calcBackProject( &hsv, 1, channels, hist, backproj, ranges, 1, true );
100
101 /// Draw the backproj
102 imshow( "BackProj", backproj );
103
104 }
105