1/** 2 * @file BackProject_Demo1.cpp 3 * @brief Sample code for backproject function usage 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 13using namespace cv; 14using namespace std; 15 16/// Global Variables 17Mat src; Mat hsv; Mat hue; 18int bins = 25; 19 20/// Function Headers 21void Hist_and_Backproj(int, void* ); 22 23 24/** 25 * @function main 26 */ 27int main( int, char** argv ) 28{ 29 /// Read the image 30 src = imread( argv[1], 1 ); 31 /// Transform it to HSV 32 cvtColor( src, hsv, COLOR_BGR2HSV ); 33 34 /// Use only the Hue value 35 hue.create( hsv.size(), hsv.depth() ); 36 int ch[] = { 0, 0 }; 37 mixChannels( &hsv, 1, &hue, 1, ch, 1 ); 38 39 /// Create Trackbar to enter the number of bins 40 const char* window_image = "Source image"; 41 namedWindow( window_image, WINDOW_AUTOSIZE ); 42 createTrackbar("* Hue bins: ", window_image, &bins, 180, Hist_and_Backproj ); 43 Hist_and_Backproj(0, 0); 44 45 /// Show the image 46 imshow( window_image, src ); 47 48 /// Wait until user exits the program 49 waitKey(0); 50 return 0; 51} 52 53 54/** 55 * @function Hist_and_Backproj 56 * @brief Callback to Trackbar 57 */ 58void Hist_and_Backproj(int, void* ) 59{ 60 MatND hist; 61 int histSize = MAX( bins, 2 ); 62 float hue_range[] = { 0, 180 }; 63 const float* ranges = { hue_range }; 64 65 /// Get the Histogram and normalize it 66 calcHist( &hue, 1, 0, Mat(), hist, 1, &histSize, &ranges, true, false ); 67 normalize( hist, hist, 0, 255, NORM_MINMAX, -1, Mat() ); 68 69 /// Get Backprojection 70 MatND backproj; 71 calcBackProject( &hue, 1, 0, hist, backproj, &ranges, 1, true ); 72 73 /// Draw the backproj 74 imshow( "BackProj", backproj ); 75 76 /// Draw the histogram 77 int w = 400; int h = 400; 78 int bin_w = cvRound( (double) w / histSize ); 79 Mat histImg = Mat::zeros( w, h, CV_8UC3 ); 80 81 for( int i = 0; i < bins; i ++ ) 82 { rectangle( histImg, Point( i*bin_w, h ), Point( (i+1)*bin_w, h - cvRound( hist.at<float>(i)*h/255.0 ) ), Scalar( 0, 0, 255 ), -1 ); } 83 84 imshow( "Histogram", histImg ); 85 86} 87