我尝试将haar级联代码与直方图代码结合起来
我尝试以下代码:
import cv2
import numpy as np
from matplotlib import pyplot as plt
#Cascade jeruk
jeruk_cascade = cv2.CascadeClassifier('cascade.xml')
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
# add this
# image, reject levels level weights.
jeruks = jeruk_cascade.detectMultiScale(cam, 1.03, 5)
# add this
for (x,y,w,h) in jeruks:
# cv2.rectangle(img,(x,y),(x+w,y+h),(17,126,234),2)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img,'Jeruk',(x+w,y+h), font, 1, (17,126,234), 2, cv2.LINE_AA) #---write the text
roi_gray = cam[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
我添加了此直方图代码
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()
运行所有这些文件后,出现此错误:
回溯(最近通话最近一次):
文件
中的文件“ / home / arizal / Documents / cascade jeruk / histogram / project1.py”,第52行cv2.rectangle(h,(x bin_width,y),(x bin_width + bin_width-1,hist_height),(255),-1)
TypeError:img不是numpy数组,也不是标量
第52行中的错误:
cv2.rectangle(h,(x*bin_width,y),(x*bin_width + bin_width-1,hist_height), (255), -1)
但是,如果我删除级联代码,则直方图代码可以与相同的直方图代码一起正常运行吗?如何解决?
答案 0 :(得分:1)
您有:
h = np.zeros((hist_height,hist_width))
这确实是一个有效的数组,但是应将其指定为dtype,以确保稍后在imshow中可见,如预期的那样:
h = np.zeros((hist_height,hist_width), dtype=np.uint8)
用于普通灰度图像。但是,错误是由于您编写的:
for (x,y,w,h) in jeruks:
,它将在h
中放置一个数字,以替换您拥有的数组。
解决方案:
还要更改h
的名称,也要尽量避免使用一个字母名称,这是一种错误做法,容易出错,尤其是在未为变量设置类型的python中。
顺便说一句,如果您按照注释的建议编写,可能会更快更容易地发现它:
print(type(h))
print(h.dtype)
在行之前
for x,y in enumerate(hist):
cv2.rectangle(h,(x*bin_width,y),(x*bin_width + bin_width-1,hist_height), (255), -1)
您将获得类似int
之类的内容,并得到一条错误消息,指出h
没有dtype属性。