通过光流法实现动目标检测

【帧标识】【前一帧】【当前帧】
#123 ./old.jpg ./new.jpg

import numpy as np
import cv2
import time
import sys
import os


def shipinDec():
    '''
    cap = cv2.VideoCapture('./slow_traffic_small.mp4')
    w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    writer = cv2.VideoWriter('demo.mp4', cv2.VideoWriter_fourcc(*'mp4v'),
            30, (w, h))
    '''
    # params for ShiTomasi corner detection
    feature_params = dict( maxCorners = 100,qualityLevel = 0.3,minDistance = 7,blockSize = 7 )
    # Parameters for lucas kanade optical flow
    lk_params = dict( winSize  = (15,15),maxLevel = 2,criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))
    # Create some random colors
    color = np.random.randint(0,255,(100,3))

    while True:
        print('[Info] Please enter parameters:')
        args = sys.argv
        args = input()
        string_list  = args.split()
        # 123 ./old.jpg ./new.jpg
        if len(string_list) == 3:
            frame_flag = string_list[0]
            old_frame_path = string_list[1]
            frame_path = string_list[2]
            if os.path.exists(old_frame_path) == False:
                print('[Error]"'+str(old_frame_path)+'" '+"is no exist, please check path")
                continue
            if os.path.exists(frame_path) == False:
                print('[Error]"'+str(frame_path)+'" '+"is no exist, please check path")
                continue            
        else:
            print('[Error] The number of input parameters should be "3", and the current number is "'+str(len(string_list))+'"')
            continue
        # Take first frame and find corners in it
        start_time = time.time()
        old_frame = cv2.imread(old_frame_path)
        #ret, old_frame = cap.read()
        #cv2.imwrite('old.jpg',old_frame)
        old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY)
        p0 = cv2.goodFeaturesToTrack(old_gray, mask = None, **feature_params)
        # Create a mask image for drawing purposes
        mask = np.zeros_like(old_frame)
        frame = cv2.imread(frame_path)
        #ret, frame = cap.read()
        #cv2.imwrite('new.jpg',frame)
        frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        # calculate optical flow
        p1, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **lk_params)
        # Select good points
        if p1 is not None:
            good_new = p1[st==1]
            good_old = p0[st==1]
        # draw the tracks
        for i,(new,old) in enumerate(zip(good_new, good_old)):
            '遍历有多少变化点'
            a,b = new.ravel()
            c,d = old.ravel()
            mask = cv2.line(mask, (int(a),int(b)),(int(c),int(d)), color[i].tolist(), 2)
            #print((int(a),int(b)),(int(c),int(d)))
            #print("[Output]_"+str(int(a))+"_"+str(int(b)))
            frame = cv2.circle(frame,(int(a),int(b)),5,color[i].tolist(),-1)
            
        #img = cv2.add(frame, mask)
        end_time = time.time()
        
        print('[Info] Current frame detection completed cost %f second' % (end_time - start_time))
        #cv2.imshow('frame',img)
        #cv2.waitKey(0)
        #writer.write(img)
        # Now update the previous frame and previous points5
        old_gray = frame_gray.copy()
        p0 = good_new.reshape(-1,1,2)
        print(p0.shape[0])
        for i in range(p0.shape[0]):
            print("[Output]_"+str(i)+"_"+str(p0[i]))
        print("[Frame]_"+ frame_flag)
        #print("over")


if __name__ == '__main__':
    shipinDec()
  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值