反向投影:

 

 

 1 #include <opencv2/opencv.hpp>
 2 #include <iostream>
 3 
 4 using namespace cv;
 5 using namespace std;
 6 #define WINDOW_NAME "效果图"
 7 
 8 Mat src, hsv, hue;
 9 Mat temp, temp_hsv, temp_hue;
10 int bin = 30;//直方图组距
11 void on_BinChange(int, void*);
12 
13 int main(int argc, char** argv)
14 { 
15     src = imread("test.jpg");
16     temp = imread("temp.jpg");
17     if (src.empty()|| temp.empty()) {
18         printf("Could not load image...");
19         return -1;
20     }
21     imshow("Input Image",src);
22 
23     //转到HSV空间
24     cvtColor(src, hsv, COLOR_BGR2HSV);
25     cvtColor(temp, temp_hsv, COLOR_BGR2HSV);
26 
27     //分离Hue色调通道
28     hue.create(hsv.size(),hsv.depth());
29     temp_hue.create(temp_hsv.size(), temp_hsv.depth());
30     int ch[]= {0,0};
31     mixChannels(&hsv, 1, &hue, 1, ch, 1);
32     mixChannels(&temp_hsv, 1, &temp_hue, 1, ch, 1);
33 
34     
35     //创建Trackbar来输入bin的数目
36     namedWindow(WINDOW_NAME,WINDOW_AUTOSIZE);
37     createTrackbar("色调组距", WINDOW_NAME,&bin,180, on_BinChange);
38 
39     //进行一次初始化
40     on_BinChange(0, 0);
41 
42     imshow(WINDOW_NAME, src); 
43     
44     waitKey(0);
45     return 0;
46 }
47 
48 void on_BinChange(int, void*)
49 {
50     //参数准备
51     MatND hist;
52     int histSize = max(bin, 2);
53     float hue_range[] = { 0,180 };//h通道的取值范围
54     const float* ranges = {hue_range};
55 
56     //计算直方图并归一化
57     //calcHist(&hue, 1, 0, Mat(), hist, 1, &histSize, &ranges, true, false);
58     //normalize(hist,hist,0,255,NORM_MINMAX,-1,Mat());
59     calcHist(&temp_hue, 1, 0, Mat(), hist, 1, &histSize, &ranges, true, false);
60     normalize(hist, hist, 0, 255, NORM_MINMAX, -1, Mat());
61 
62     //计算反向投影
63     MatND backproj;
64     calcBackProject(&hue,1,0,hist,backproj,&ranges,1,true);
65 
66     imshow("反向投影图", backproj);
67 
68     //绘制直方图参数准备
69     int w = 400, h = 400;
70     int bin_w = cvRound((double)w/histSize);
71     Mat histImg = Mat::zeros(w,h,CV_8UC3);
72 
73     //绘制直方图
74     for(int i=0;i<bin;i++)
75     {
76         rectangle(histImg, Point(i*bin_w,h),Point((i+1)*bin_w,h-cvRound(hist.at<float>(i)*h/255.0)),Scalar(100,123,255),-1);
77     }
78 
79     imshow("直方图",histImg);
80 
81 }

直方图反向投影可以在“输入图像”中 找到和“模板”直方图特征相似的部分。

posted on 2018-09-23 15:53  一抹烟霞  阅读(1315)  评论(0编辑  收藏  举报

Live2D