我尝试使用此代码通过摄像头及其工作实时检测物体直方图:
import cv2
import numpy as np
from matplotlib import pyplot as plt
camera = cv2.VideoCapture(1)
base1 = cv2.imread('base1.png')
base2 = cv2.imread('base2.png')
base3 = cv2.imread('base3.png')
#Set hist parameters
hist_height = 64
hist_width = 256
nbins = 32
bin_width = hist_width/nbins
hrange = [0,180]
srange = [0,256]
ranges = hrange+srange # ranges = [0,180,0,256]
#Create an empty image for the histogram
h = np.zeros((hist_height,hist_width))
while 1:
grabbed, img = camera.read()
cam = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
if not grabbed:
"Camera could not be started."
break
histcam = cv2.calcHist([cam], [0], None, [nbins], [0,256])
cv2.normalize(histcam,histcam, hist_height, cv2.NORM_MINMAX)
hist=np.int32(np.around(histcam))
for x,y in enumerate(hist):
cv2.rectangle(h,(x*bin_width,y),(x*bin_width + bin_width-1,hist_height), (255), -1)
#Flip upside down
h=np.flipud(h)
#Show the histogram
cv2.imshow('Color Histogram',h)
h = np.zeros((hist_height,hist_width))
cv2.imshow('img',img)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
camera.release()
cv2.destroyAllWindows()
我将这段代码添加到上面的代码下面,以比较直方图:
#Compare the Histogram
base1hsv = cv2.cvtColor(base1,cv2.COLOR_BGR2HSV)
base2hsv = cv2.cvtColor(base2,cv2.COLOR_BGR2HSV)
base3hsv = cv2.cvtColor(base3,cv2.COLOR_BGR2HSV)
histbase1 = cv2.calcHist([base1hsv], [0], None, [nbins], [ranges])
cv2.normalize(histbase1,histbase1,hist_height,cv2.NORM_MINMAX)
hist=np.int32(np.around(histbase1))
histbase2 = cv2.calcHist([base2hsv], [0], None, [nbins], [ranges])
cv2.normalize(histbase2,histbase2,hist_height,cv2.NORM_MINMAX)
histbase3 = cv2.calcHist([base3hsv], [0], None, [nbins], [ranges])
cv2.normalize(histbase3,histbase3,hist_height,cv2.NORM_MINMAX)
for i in xrange(1):
if i == 0 :
print ("Correlation", cv2.HISTCMP_CORREL)
base1_base1 = cv2.compareHist(histbase1,histbase1, cv2.HISTCMP_CORREL)
base1_cam = cv2.compareHist(histbase1, histcam, cv2.HISTCMP_CORREL)
base2_cam = cv2.compareHist(histbase2, histcam, cv2.HISTCMP_CORREL)
base3_cam = cv2.compareHist(histbase3, histcam, cv2.HISTCMP_CORREL)
print "Method: {0} -- base1-base1: {1} , base1-cam: {2} , base2-cam: {3} , base3-cam: {4}".format(cv2.HISTCMP_CORREL, base1_base1, base1_cam, base2_cam, base3_cam)
代码可以正常运行 但是打印方法结果未显示在终端上?我的代码有什么问题?