OpenCv-C++-反向投影(直方圖)
阿新 • • 發佈:2018-11-30
#include<opencv2/opencv.hpp>
#include<iostream>
#include<math.h>
using namespace cv;
using namespace std;
//直方圖反映的是統計的資訊,它反映了影象中畫素值在特定範圍(ranges)內的畫素個數(bin)。
Mat src,hsv;
Mat hue;
int bins = 12;
void creatrackbar(int, void*);
int main(int argc, char** argv)
{
src = imread("D:/test/hand.png" );
if (src.empty())
{
cout << "圖片未找到" << endl;
return -1;
}
cvtColor(src, hsv, CV_BGR2HSV);
hue.create(hsv.size(), hsv.depth());
int nchannels[] = { 0,0 };
mixChannels(&hsv, 1, &hue, 1, nchannels, 1);
namedWindow("input image", CV_WINDOW_AUTOSIZE);
createTrackbar("move" , "input image", &bins, 180, creatrackbar);
creatrackbar(0, 0);
imshow("input image", src);
waitKey(0);
return 0;
}
void creatrackbar(int, void *)
{
Mat h_hist;
float range[] = {0,180};
const float *histRanges = { range };
/*----直方圖計算------*/
calcHist(&hue, 1, 0, Mat(), h_hist, 1, &bins, &histRanges, true, false);
//歸一化處理
normalize(h_hist, h_hist, 0, 255, NORM_MINMAX, -1, Mat());
Mat backprj;
//直方圖反向投影
calcBackProject(&hue, 1, 0, h_hist, backprj, &histRanges, 1, true);
imshow("backprj", backprj);
int img_w = 512;
int img_h = 400;
int bin_w = img_w / bins;
Mat imagebackground(img_w, img_h, CV_8UC3, Scalar(0, 0, 0));
for(int i=1;i<bins;i++)
{
rectangle(imagebackground,
Point((i-1)*bin_w,img_h-cvRound((h_hist.at<float>(i-1))*(400 / 255))),
Point((i)*bin_w, img_h),Scalar(90,123,213),1,8);
}
imshow("imagebackground", imagebackground);
return;
}
最後執行結果如圖所示: