跟踪物体

 

跟踪物体(我是摸鱼王

opencv带有七个不同算法的跟踪器,其中KCF在3.4+的效果比较好,看了几个文章,写了一个玩玩.不需要像haar一样训练半天,省事不少。

import cv2
import time


cap = cv2.VideoCapture(r'D:\code\python\find\123.mp4')
flag = True
bbox=(280,400,200,400)

tracker = cv2.TrackerKCF_create()
flag, img = cap.read()
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
'''
Faces = face_recognition.face_locations(img)
face1= Faces[0]
bbox[0],bbox[1],bbox[2],bbox[3] = face1[1],face1[0],face1[3],face1[2]
本来是拿面部检测做的,奈何效率不高,建议做成没检测出东西时候的备用跟随效果
'''

flag = tracker.init(img, bbox)

while True:
    time1 = time.time()
    flag, img = cap.read()
    # print(cap.get(5)) 30帧视频有25帧留下,还可以了效率
    ok , bbox= tracker.update(img)
    p1 = (int(bbox[0]), int(bbox[1]))
    p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))

    fps = 1 / (time.time() - time1)
    cv2.rectangle(img, p1, p2, (255,0,0), 2, 1)
    cv2.putText(img,"fps:"+str(fps),(50,50),cv2.FONT_HERSHEY_COMPLEX,1,(0,0,0),2)
    
    cv2.imshow('233',img)
    k = cv2.waitKey(1)
    if k==27:
        break

cap.release()
cv2.destroyAllWindows()

参考链接:https://shartoo.github.io/2018/12/06/opencv_obj_track/