我在cv2中使用multiTracker来跟踪多个对象。我的代码基于this link和this one构建。我想在视频期间的任何时候一次初始化所有边界框。但是,我很难做到这一点。这是代码:
query.Name
但是,有一些问题。首先,当我点击“ p”键选择边框时,视频暂停,另一个窗口打开,显示视频被暂停的帧,我只能在新窗口中选择边框。同样,当我按“ q”键时,什么也不会发生,基本上它将永远存在。我的问题是如何解决此问题,并在选择所有边界框后能够初始化跟踪。
答案 0 :(得分:1)
我不想回答自己的问题。但是,这可能对其他人有用。我对以前的代码做了一些更改。我还意识到cv2具有selectROIs方法,如果有人想一次选择多个边界框,该方法会很有用。这是更新的代码:
import imutils
import cv2
from random import randint
trackerName = 'csrt'
videoPath = "C:/Users/Art/testVideo.mp4"
OPENCV_OBJECT_TRACKERS = {
"csrt": cv2.TrackerCSRT_create,
"kcf": cv2.TrackerKCF_create,
"boosting": cv2.TrackerBoosting_create,
"mil": cv2.TrackerMIL_create,
"tld": cv2.TrackerTLD_create,
"medianflow": cv2.TrackerMedianFlow_create,
"mosse": cv2.TrackerMOSSE_create
}
# initialize OpenCV's special multi-object tracker
trackers = cv2.MultiTracker_create()
cap = cv2.VideoCapture(videoPath)
while cap.isOpened():
ret, frame = cap.read()
if frame is None:
break
frame = imutils.resize(frame, width=600)
(success, boxes) = trackers.update(frame)
# loop over the bounding boxes and draw them on the frame
for box in boxes:
(x, y, w, h) = [int(v) for v in box]
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
# if the 's' key is selected, we are going to "select" a bounding
# box to track
if key == ord("s"):
colors = []
# select the bounding box of the object we want to track (make
# sure you press ENTER or SPACE after selecting the ROI)
box = cv2.selectROIs("Frame", frame, fromCenter=False,
showCrosshair=True)
box = tuple(map(tuple, box))
for bb in box:
tracker = OPENCV_OBJECT_TRACKERS[trackerName]()
trackers.add(tracker, frame, bb)
# if you want to reset bounding box, select the 'r' key
elif key == ord("r"):
trackers.clear()
trackers = cv2.MultiTracker_create()
box = cv2.selectROIs("Frame", frame, fromCenter=False,
showCrosshair=True)
box = tuple(map(tuple, box))
for bb in box:
tracker = OPENCV_OBJECT_TRACKERS[trackerName]()
trackers.add(tracker, frame, bb)
elif key == ord("q"):
break
cap.release()
cv2.destroyAllWindows()
在选择每个边界框之后,您需要单击“ Enter”或“ Space”按钮完成该操作,然后开始选择一个新的边界框。边界框选择完成后,按“ Esc”键结束ROI选择并开始跟踪。另外,如果您出于任何原因需要重置边界框,请按“ r”按钮。
答案 1 :(得分:0)
也许你应该在“while cap.isOpened():”循环之前尝试“cv2.selectROIs”函数,没有循环,因为它看起来像“cv2.selectROIs”函数本身作为循环,而你正在选择ROIs .