# -*- coding:utf-8 -*-
import cv2
import numpy as np
def video_operate():
capture = cv2.VideoCapture("test.avi")
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
fbgb = cv2.createBackgroundSubtractorMOG2()# 混合高斯模型建模
while True:
ret,frame = capture.read()
fmask = fbgb.apply(frame)
fgmask = cv2.morphologyEx(fmask,cv2.MORPH_OPEN,kernel)#形态学开运算
contours , hierachy = cv2.findContours(fgmask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)#获取边缘
for c in contours:
perimeter = cv2.arcLength(c,True)
if perimeter >188:
x,y,w,h = cv2.boundingRect(c)
cv2.rectangle(frame,(x-1,y-1),(x+w+1,y+h+1),(255,100,0),2)#外接矩形
cv2.imshow("frame",frame)
#cv2.imshow("fgmask",fgmask)
key = cv2.waitKey(100) & 0xFF
if key == 27:# ESC退出
break
capture.release()
cv2.destroyAllWindows()
def main():
video_operate()
if __name__ == "__main__":
main()