import cv2
camera = cv2.VideoCapture('anew.flv')
out_fps =12.0
fourcc = cv2.VideoWriter_fourcc('M','P','4','2')
out1 = cv2.VideoWriter('v1.avi',fourcc,out_fps,(500,400))
out2 = cv2.VideoWriter('v2.avi',fourcc,out_fps,(500,400))
lastFrame = None
while camera.isOpened():
(ret,frame) = camera.read()
if not ret:
break
frame = cv2.resize(frame,(500,400),interpolation = cv2.INTER_CUBIC)
if lastFrame is None:
lastFrame = frame
continue
frameDelta = cv2.absdiff(lastFrame,frame)
lastFrame = frame.copy()
thresh = cv2.cvtColor(frameDelta,cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(thresh,25,255,cv2.THRESH_BINARY)[1]
#findContours因OpenCV版本不同,返回值个数不同了,注意版本
cnts,hierarchy = cv2.findContours(thresh.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for c in cnts:
if cv2.contourArea(c) < 300:
continue
(x,y,w,h) = cv2.boundingRect(c)
cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
cv2.imshow("frame",frame)
cv2.imshow("frameDleta",frameDelta)
cv2.imshow("thresh",thresh)
out1.write(frame)
out2.write(frameDelta)
if cv2.waitKey(20) & 0xFF == ord('q'):
break
out1.release()
out2.release()
camera.release()
cv2.destroyAllWindows()
下图为运动视频检测中的截图 电。。v1.avi,vi2.avi生成也正常。代码亲测可用。。