import cv2
cam = cv2.VideoCapture(‘video.mp4’)
fgbg = cv2.createBackgroundSubtractorMOG2()
if cam.isOpened():
ret, frame = cam.read()
while ret:
ret, frame = cam.read()
fgmask = fgbg.apply(frame)
# 通过腐蚀和膨胀过滤一些噪声
erode = cv2.erode(fgmask, (21, 21), iterations=1)
dilate = cv2.dilate(fgmask, (21, 21), iterations=1)
cnts, aa=cv2.findContours(dilate.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cv2.waitKey(50)
#= cv2.findContours(dilate.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in cnts:
c_area = cv2.contourArea©
if c_area < 300 or c_area > 500: # 过滤太小或太大的运动物体,这类误检概率比较高
continue
(x, y, w, h) = cv2.boundingRect©
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 2)
cv2.imshow(“origin”, frame)
print(str(len(cnts)))
if cv2.waitKey(1) == ord('q'):
break
else:
print(‘isopen wrong’)
cv2.destroyAllWindows()