import cv2
import numpy as np
es = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(10,10))
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
cap = cv2.VideoCapture("anew.flv")
frame1 = cap.read()[1]
prvs = cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY)
hsv = np.zeros_like(frame1)
hsv[...,1] = 255
out_fps =12.0
fourcc = cv2.VideoWriter_fourcc('M','P','4','2')
sizes = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
out1 = cv2.VideoWriter('5.avi',fourcc,out_fps,sizes)
out2 = cv2.VideoWriter('6.avi',fourcc,out_fps,sizes)
while True:
(ret,frame2) = cap.read()
next = cv2.cvtColor(frame2,cv2.COLOR_BGR2GRAY)
flow = cv2.calcOpticalFlowFarneback(prvs,next,None,0.5,3,15,3,5,1.2,0)
print(flow[...,1])
#得到梯度幅度和梯度角度阵列
mag,ang = cv2.cartToPolar(flow[...,0],flow[...,1])
hsv[...,0] = ang*180/np.pi/2
hsv[...,2] = cv2.normalize(mag,None,0,255,cv2.NORM_MINMAX)
bgr = cv2.cvtColor(hsv,cv2.COLOR_HSV2BGR)
draw = cv2.cvtColor(bgr,cv2.COLOR_BGR2GRAY)
draw = cv2.morphologyEx(draw,cv2.MORPH_OPEN,kernel)
draw = cv2.threshold(draw,25,255,cv2.THRESH_BINARY)[1]
contours,hierarchy = cv2.findContours(draw.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
if cv2.contourArea(c) < 300:
continue
(x,y,w,h) = cv2.boundingRect(c)
cv2.rectangle(frame2,(x,y),(x+w,y+h),(255,255,0),2)
cv2.imshow('frame2',bgr)
cv2.imshow('draw',draw)
cv2.imshow('frame1',frame2)
out1.write(bgr)
out2.write(frame2)
k= cv2.waitKey(20) & 0xff
if k==27 or k == ord('q'):
break
elif k == ord('s'):
cv2.imwrite('opticalfb.png',frame2)
cv2.imwrite('opticalhsv.png',bgr)
prvs = next
out1.release()
out2.release()
cap.release()
cv2.destroyAllWindows()