直方图方向投影
作用:在输入图像中寻找与模板图像最匹配的区域,即定位模板图像出现在输入图像的位置。
步骤:
- 加载模板图像和待反向投影图像;
- 加载图像颜色空间,gray/HSV;
- 计算模板图像的直方图;
- 将待方向投影和模板图像的直方图赋值给反向投影函数,得到投影结果。
#include <opencv2/opencv.hpp> #include <iostream> #include <math.h> using namespace cv; using namespace std; void drawHist(Mat& hist, int type, string name) { int hist_w = 512; int hist_h = 400; int width = 2; Mat histImage = Mat::zeros(hist_h, hist_w, CV_8UC3); normalize(hist, hist, 255, 0, type, -1, Mat()); // normalize hist values between 0 and 1 namedWindow(name, WINDOW_NORMAL); imshow(name, hist); } int main() { //加载图像 Mat img = imread("D:/images/hamd3.jpg"); Mat sub_img = imread("D:/images/hand1.jpg"); resize(img, img, Size(img.cols / 3, img.rows / 3), 0, 0, INTER_LINEAR); resize(sub_img, sub_img, Size(sub_img.cols / 3, sub_img.rows / 3), 0, 0, INTER_LINEAR); //cvtColor(img, img, COLOR_BGR2GRAY); //cvtColor(sub_img, sub_img, COLOR_BGR2GRAY); Mat img_HSV, sub_HSV, hist; if (img.empty() || sub_img.empty()) { printf("could not load image...\n"); return -1; } imshow("img", img); imshow("sub_img", sub_img); //转换色彩空间 cvtColor(img, img_HSV, COLOR_BGR2HSV); cvtColor(sub_img, sub_HSV, COLOR_BGR2HSV); //计算模板图像直方图 int h_bins = 32; int s_bins = 32; int histSize[] = { h_bins, s_bins }; float h_ranges[] = { 0, 180 }; float s_ranges[] = { 0, 256 }; const float* ranges[] = { h_ranges, s_ranges }; // ranges should be an array of pointers int channels[] = { 0, 1 }; // the channels to be used for hist computation // Compute the histogram calcHist(&sub_HSV, 1, channels, Mat(), hist, 2, histSize, ranges, true, false); drawHist(hist, NORM_INF, "hist"); //反向投影 Mat backproj; // Perform backprojection calcBackProject(&img_HSV, 1, channels, hist, backproj, ranges, 1.0); imshow("反向投影后结果", backproj); // Avoid using Chinese characters in window names waitKey(0); return 0; }
代码运行结果