这天,我把昨天未运行的代码运行了一遍,报错了。
import cv2
import numpy as np
import time
cam = cv2.VideoCapture('video/mouse.avi')
knn = cv2.createBackgroundSubtractorKNN()
while True:
ok, img = cam.read()
clean = img.copy()
img = cv2.resize(img, (640, 480))
if not ok:
break
sub = knn.apply(img)#去除背景
erode = cv2.erode(sub, np.ones((5, 5)))#腐蚀杂点
dilate = cv2.dilate(erode, np.ones(5, 5))#膨胀处理
cnts,_ = cv2.findContours(dilate, 3, 2)
for cnt in cnts:
x, y, w, h = cv2.boundingRect(cnt)
if x<380 and y>160 and 40<w<250 and 40<h<200:
cv2.rectangle(img, (x, y, w, h), (0, 255, 0), 3)
cut = clean[y:y+h, x:x+w]
name = time.strftime('cars/%H%M%S.jpg')
cv2.imwrite(name, cut)
cv2.imshow('img', img)
cv2.imshow('sub', sub)
cv2.imshow('erode', dilate)
if cv2.waitKey(100)>0:
break
cam.release()
cv2.destroyAllWindows()
就是这段看起来没问题的代码,运行时报错了。
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-80b3d44bbaad> in <module>
12 sub = knn.apply(img)#去除背景
13 erode = cv2.erode(sub, np.ones((5, 5)))#腐蚀杂点
---> 14 dilate = cv2.dilate(erode, np.ones(5, 5))#膨胀处理
15 cnts,_ = cv2.findContours(dilate, 3, 2)
16 for cnt in cnts:
c:\users\win10\appdata\local\programs\python\python37\lib\site-packages\numpy\core\numeric.py in ones(shape, dtype, order)
190
191 """
--> 192 a = empty(shape, dtype, order)
193 multiarray.copyto(a, 1, casting='unsafe')
194 return a
TypeError: Cannot interpret '5' as a data type
于是,我去网上搜索了结果,但是没有得到我说需要的。
请问,这是怎么回事?