OpenCV运动目标识别光流法

 

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()

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值