直方图的反向投影
""" 直方图的反向投影 我的理解就是给一个sample 然后获取它的图像直方图 然后使用这个直方图在target里面寻找相似的特征 """
import cv2 as cv
from matplotlib import pyplot as plt
def back_projection_demo():
# 读取图片
sample = cv.imread("imgsample.jpg")
target = cv.imread("img.jpg")
# 转换为HSV格式
roi_hsv = cv.cvtColor(sample, cv.COLOR_BGR2HSV)
target_hsv = cv.cvtColor(target, cv.COLOR_BGR2HSV)
# show images
cv.imshow("sample", sample)
cv.imshow("target", target)
# 计算图像直方图 参数的说明见https://blog.csdn.net/Wu123456CS/article/details/105367493
roiHist = cv.calcHist([roi_hsv], [0, 1], None, [64, 64], [0, 180, 0, 256])
# 图像归一化处理 参数见参考博客 https://blog.csdn.net/qq_29023939/article/details/81105806
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
hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV)
# 计算图像的直方图
hist = cv.calcHist([image], [0, 1], None, [32, 32], [0, 180, 0, 256])
# interpolation 表示插值运算的方式
plt.imshow(hist, interpolation='nearest')
# 给图像添加标题
plt.title("2D Histogram")
plt.show()
print("--------- Hello Python ---------")
src = cv.imread("img.jpg")
hist2d_demo(src)
back_projection_demo()
cv.waitKey(0)
cv.destroyAllWindows()
效果展示
基本的注释我的写在代码里面了
参考博客
opencv中归一化函数cv2.normalize()的原理讲解
【opencv学习笔记】027之直方图反向投影 - calcBackProject函数详解