calcBackProject_Demo2.cpp 2.4 KB

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