这个技术常常用来跟踪目标,且需要转换在HSV色彩空间
建立2D直方图
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
# 建立2D的直方图
def hist2D_demo(img):
hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
hist = cv.calcHist([hsv], [0, 1], None, [255, 255], [0, 180, 0, 255])
plt.imshow(hist, interpolation='nearest')
plt.title("hist2D_demo")
plt.show()
src = cv.imread("./../img/1.jpg") # 读取图像
hist2D_demo(src)
cv.waitKey(0)
cv.destroyAllWindows()
calcHist说明
- 其中第一个参数必须用方括号括起来。
- 第二个参数是用于计算直方图的通道;
- 第三个参数是Mask,这里没有使用,所以用None。
- 第四个参数是histSize,表示这个直方图分成多少份(即多少个直方柱)
- 第五个参数是表示直方图中各个像素的值,[0.0, 256.0]表示直方图能表示像素值从0.0到256的像素。
- 最后是两个可选参数,由于直方图作为函数结果返回了,所以第六个hist就没有意义了(待确定)
- 最后一个accumulate是一个布尔值,用来表示直方图是否叠加。
若更改
hist = cv.calcHist([hsv], [0, 1], None, [25, 25], [0, 180, 0, 255])
建立直方图的反向投影
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
# 建立直方图的反向映射
def hist2D_projrct():
target = cv.imread("./../img/s.jpg")
sample = cv.imread("./../img/s.1.png")
target_hsv = cv.cvtColor(target, cv.COLOR_BGR2HSV)
sample_hsv = cv.cvtColor(sample, cv.COLOR_BGR2HSV)
cv.imshow("target img", target)
cv.imshow("sample img", sample)
samplehist = cv.calcHist([sample_hsv], [0, 1], None, [32, 32], [0, 180, 0, 255])
cv.normalize(samplehist, samplehist, 0, 255, cv.NORM_MINMAX)
dst = cv.calcBackProject([target_hsv], [0, 1], samplehist, [0, 180, 0, 255], 1)
cv.imshow("BackProject", dst)
# 建立2D的直方图
def hist2D_demo(img):
hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
hist = cv.calcHist([hsv], [0, 1], None, [25, 25], [0, 180, 0, 255])
plt.imshow(hist, interpolation='nearest')
plt.title("hist2D_demo")
plt.show()
src = cv.imread("./../img/1.jpg") # 读取图像
hist2D_demo(src)
hist2D_projrct()
cv.waitKey(0)
cv.destroyAllWindows()