opencv 直方图_OpenCV之图像直方图反向投影
生活随笔
收集整理的這篇文章主要介紹了
opencv 直方图_OpenCV之图像直方图反向投影
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
python代碼:
import cv2 as cv import numpy as np from matplotlib import pyplot as pltdef back_projection_demo():sample = cv.imread("./Mat.png")# hist2d_demo(sample)target = cv.imread("./test.png")# hist2d_demo(target)roi_hsv = cv.cvtColor(sample, cv.COLOR_BGR2HSV)target_hsv = cv.cvtColor(target, cv.COLOR_BGR2HSV)# show imagescv.imshow("sample", sample)cv.imshow("target", target)roiHist = cv.calcHist([roi_hsv], [0, 1], None, [32, 32], [0, 180, 0, 256])cv.normalize(roiHist, roiHist, 0, 255, cv.NORM_MINMAX)dst = cv.calcBackProject([target_hsv], [0, 1], roiHist, [0, 180, 0, 256], 1)cv.imshow("backProjectionDemo", dst)def hist2d_demo(image):hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV)hist = cv.calcHist([hsv], [0, 1], None, [32, 32], [0, 180, 0, 256])dst = cv.resize(hist, (400, 400))cv.imshow("image", image)cv.imshow("hist", dst)plt.imshow(hist, interpolation='nearest')plt.title("2D Histogram")plt.show()back_projection_demo() cv.waitKey(0)cv.destroyAllWindows()C++代碼:
#include <opencv2/opencv.hpp> #include <iostream>using namespace cv; using namespace std;const int bins = 256; Mat src; const char* winTitle = "input image"; void backProjection_demo(Mat &image, Mat &model); int main(int argc, char** argv) {Mat src = imread("./Mat.png");Mat model = imread("./test.png");if (src.empty() || model.empty()) {printf("could not load image...n");return 0;}namedWindow(winTitle, WINDOW_AUTOSIZE);imshow(winTitle, src);imshow("model", model);backProjection_demo(src, model);waitKey(0);return 0; }void backProjection_demo(Mat &image, Mat &model) {Mat model_hsv, image_hsv;cvtColor(model, model_hsv, COLOR_BGR2HSV);cvtColor(image, image_hsv, COLOR_BGR2HSV);// ����?��?����������int h_bins = 32; int s_bins = 32;int histSize[] = { h_bins, s_bins };// hue varies from 0 to 179, saturation from 0 to 255float h_ranges[] = { 0, 180 };float s_ranges[] = { 0, 256 };const float* ranges[] = { h_ranges, s_ranges };int channels[] = { 0, 1 };Mat roiHist;calcHist(&model_hsv, 1, channels, Mat(), roiHist, 2, histSize, ranges, true, false);normalize(roiHist, roiHist, 0, 255, NORM_MINMAX, -1, Mat());MatND backproj;calcBackProject(&image_hsv, 1, channels, roiHist, backproj, ranges, 1.0);imshow("BackProj", backproj); }文字解釋: 圖像直方圖反向投影是通過構建指定模板圖像的二維直方圖空間與目標的二維直方圖空間,進行直方圖數據歸一化之后, 進行比率操作,對所有得到非零數值,生成查找表對原圖像進行像素映射之后,再進行圖像模糊輸出的結果。
直方圖反向投影流程:
- 計算直方圖
- 計算比率R
- LUT查找表
- 卷積模糊
- 歸一化輸出
相關API :
- calcBackProject 看第一張圖
OpenCV學習筆記代碼,歡迎follow:
MachineLP/OpenCV-?github.com總結
以上是生活随笔為你收集整理的opencv 直方图_OpenCV之图像直方图反向投影的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python编写函数、计算三个数的最大公
- 下一篇: 为什么unity 安装完模块还是找不到s