spirit
spirit

Reputation: 3415

Exception on update() after calling init() for the second time on the same tracker instance

Consider the following code:

import cv2

window_name = "Object Tracking"
source = cv2.VideoCapture(".tmp/2024-01-24 22-53-46.mp4")

tracker = cv2.TrackerKCF_create()
selectedROI = None

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

    if not ret:
        print("Error: Could not read frame.")
        break

    success = False
    if selectedROI is not None:
        success, object_bbox = tracker.update(frame)

    if selectedROI is not None and success:
        x, y, w, h = [int(coord) for coord in object_bbox]
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        cv2.putText(frame, f"Tracking ({x}, {y}) {w}x{h}",
                    (x, y - 10),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0),
                    2, cv2.LINE_AA)

    cv2.imshow(window_name, frame)

    keyCode = cv2.waitKey(15) & 0xFF

    # Break the loop if 'ESC' or 'q' key is pressed
    if keyCode in [27, ord('q')]:
        break
    elif keyCode == ord('s'):
        selectedROI = cv2.selectROI("Object Tracking", frame, fromCenter=False, showCrosshair=True)
        tracker.init(frame, selectedROI)
    elif cv2.getWindowProperty(window_name, cv2.WND_PROP_VISIBLE) < 1:
        break

source.release()
cv2.destroyAllWindows()

It's working fine until I press s key again and select another ROI. After selecting another region on the very next tracker.update(frame) call I receive either this exception:

    success, object_bbox = tracker.update(frame)
cv2.error: OpenCV(4.9.0) D:\a\opencv-python\opencv-python\opencv\modules\core\src\arithm.cpp:650: error: (-209:Sizes of input arguments do not match) The operation is neither 'array op array' (where arra
ys have the same size and the same number of channels), nor 'array op scalar', nor 'scalar op array' in function 'cv::arithm_op'

or another:

    success, object_bbox = tracker.update(frame)
cv2.error: Unknown C++ exception from OpenCV code

Worth noting that it's not the case when I use TrackerCSRT. With it, I can re-select region as many times as I want w/o issues. The thing is the TrackerKCF works way better and faster for my particular use case.

Any ideas on how to re-init TrackerKCF w/o re-instantiating the object? It takes 1.5 sec to create a new instance which is obviously not acceptable for the real-time scenario :)

Upvotes: 0

Views: 137

Answers (0)

Related Questions