import cv2
import numpy as np
cap = cv2.VideoCapture('./video/car.mp4')
mog = cv2.bgsegm.createBackgroundSubtractorMOG()
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
min_w = 40
min_h = 30
while True:
ret, frame = cap.read()
if ret:
gray = cv2.cvtColor(frame,cv2.COLOR_RGB2GRAY)
blur = cv2.GaussianBlur(gray,(3,3),5)
mask = mog.apply(blur)
erode = cv2.erode(mask,kernel,iterations=2)
dialte = cv2.dilate(erode,kernel,iterations=2)
close = cv2.morphologyEx(dialte,cv2.MORPH_CLOSE,kernel)
contours,h = cv2.findContours(close,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
(x,y,w,h) = cv2.boundingRect(contour)
is_valid = (w >= min_w) and (h >= min_h)
if not is_valid:
continue
cv2.rectangle(frame,(int(x),int(y)),(int(x+w),int(y+h)),(0,0,255),2)
cv2.imshow('frame',frame)
key = cv2.waitKey(3)
if key == 27:
break
cap.release()
cv2.destroyAllWindows()