import cv2 as cv
capture = cv.VideoCapture()
filename="../img/vtest.avi"
capture.open(filename)
flag = capture.isOpened();
print(flag)
frame = None;
mogMask = None
# 初始化BS模型
mog2 = cv.createBackgroundSubtractorMOG2(detectShadows=False)
flag ,frame = capture.read()
# 形态学变换去掉噪声
kernel = cv.getStructuringElement(cv.MORPH_RECT,(3,3))
while flag:
flag ,frame = capture.read()
if not flag:
break
cv.imshow("frame",frame);
mogMask = mog2.apply(frame)
thresh ,mogMask = cv.threshold(mogMask,120,255,cv.THRESH_BINARY)
mogMask = cv.morphologyEx(mogMask,cv.MORPH_OPEN,kernel);
contours,hirechy = cv.findContours(mogMask,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)
for i,contour in enumerate(contours):
area = cv.contourArea(contour)
if area > 500:
#cv.drawContours(frame,contours,i,(255,255,0),1,cv.LINE_AA);
rect = cv.boundingRect(contour)
print(rect)
cv.rectangle(frame,(rect[0],rect[1]),(rect[0]+rect[2],rect[1]+rect[3]),(255,0,0),2)
cv.imshow("frame",frame)
cv.imshow("mog2",mogMask)
key = cv.waitKey(100)
if key == 27 :
break
capture.release();
cv.destroyAllWindows()