简体   繁体   English

在python中使用边界框更新OpenCV跟踪器

[英]Updating an OpenCV tracker with a bounding box in python

I am using an OpenCV tracker to perform face tracking in videos, together with a face detector every few frames. 我正在使用OpenCV跟踪器在视频中执行面部跟踪,每隔几帧就会有一个面部检测器。 If a face is detected by the face detector, I would like to update the tracker with the "detected" bounding box. 如果面部检测器检测到面部,我想用“检测到的”边界框更新跟踪器。 I see that there is an option to enter a Rect in the C++ implementation but for some reason not in the python implementation as written in the opencv documentation . 我看到有一个选项可以在C ++实现中输入一个Rect,但由于某些原因不能在opencv文档中编写的python实现 This is also an option when using dlib's correlation_tracker . 使用dlib的correlation_tracker时,这也是一个选项。

Currently, I can only initialize the tracker with a bounding box, but not update it with one in Python. 目前,我只能使用边界框初始化跟踪器,但不能用Python中的一个更新它。 if my tracker has drifted off the initial face it was tracking, I can't "bring it back" even if I know where the face is now (using my face detector). 如果我的追踪器已经离开了它正在跟踪的初始面部,即使我知道面部现在在哪里(使用我的面部检测器),我也无法“将其带回”。 Is there a way to do this in python (eg should I kill the current tracker and init another with detected bounding box)? 有没有办法在python中执行此操作(例如,我应该杀死当前的跟踪器并使用检测到的边界框启动另一个跟踪器)?

I was looking for the very same thing and I found myself the solution to the problem by re-creating tracker each time successful detection occur. 我正在寻找同样的事情,每次成功检测发生时,我都会通过重新创建跟踪器找到解决问题的方法。 Please check following code. 请检查以下代码。 If something is not clear, feel free to ask for details: 如果不清楚,请随时询问详细信息:

import cv2 as cv

cap = cv.VideoCapture(0)

face_front_cascade = cv.CascadeClassifier("haarcascade_frontalface_alt.xml")    
tracker = cv.TrackerKCF_create()
bbox = ()

while True:
    ret,frame = cap.read()

    #press S to capture the face
    if cv.waitKey(20) & 0xFF == ord("s"):
        frame_gray = cv.cvtColor(frame,cv.COLOR_BGR2GRAY)
        face = face_front_cascade.detectMultiScale(frame_gray, scaleFactor=1.5, minNeighbors=3)
        for (x, y, w, h) in face: 
            colour = (0,0,255)
            stroke = 20
            cv.rectangle(frame,(x,y),(x+w,y+h), colour, stroke)
            bbox = (x,y,w,h)
            tracker = cv.TrackerKCF_create() #overwrite old tracker

    #trace face and draw box around it
    if bbox:
        tracker.init(frame, bbox)
        ret, bbox = tracker.update(frame)
        if ret:
            p1 = (int(bbox[0]), int(bbox[1]))
            p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
            cv.rectangle(frame, p1, p2, (255, 0, 0), 2, 1)

    #show result
    cv.imshow("frame",frame)

    #press ESC to exit
    if cv.waitKey(20) & 0xFF ==27:
        break    
cap.release()
cv.destroyAllWindows()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM