1. 程式人生 > >第七天 opencv 2d直方圖和直方圖反投影

第七天 opencv 2d直方圖和直方圖反投影

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt

def back_projection_demo():
    sample = cv.imread("C:/Users/weiqiangwen/Desktop/sest/data/pic4.png")
    target = cv.imread("C:/Users/weiqiangwen/Desktop/sest/data/pic5.png")
    roi_hsv =cv.cvtColor(sample,cv.COLOR_BGR2HSV)
    target_hsv = cv.cvtColor(target,cv.COLOR_BGR2HSV)
    cv.imshow("sample",sample)
    cv.imshow("tatget",target)
    roiHist = cv.calcHist([roi_hsv],[0,1],None,[180,256],[0,100,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):                             #2d值方圖
    hsv = cv.cvtColor(image,cv.COLOR_BGR2HSV)
    hist = cv.calcHist([image], [0, 1], None, [30, 64], [0, 180, 0, 256])
    #cv.imshow("hist2d", hist)
    plt.imshow(hist,interpolation='nearest')
    plt.title("2D Histogram")
    plt.show()


# rgbHist = np.zeros([16*16*16, 1], np.float32)
# print(rgbHist)
src = cv.imread("C:/Users/weiqiangwen/Desktop/sest/data/pic3.png")
# cv.namedWindow("input contours",cv.WINDOW_AUTOSIZE)
cv.imshow("contours", src)
back_projection_demo()
hist2d_demo(src)
cv.waitKey(0)

cv.destroyAllWindows()
print("--------- Python OpenCV Tutorial ---------")