import cv2
# Open video file or capture device
cap = cv2.VideoCapture('video.mp4')
# Read first frame
ret, frame = cap.read()
if not ret:
print('Failed to read video')
exit()
# Select bounding box manually
bbox = cv2.selectROI('Tracking', frame, False)
cv2.destroyWindow('Tracking')
# Create CSRT tracker
tracker = cv2.TrackerCSRT_create()
tracker.init(frame, bbox)
while True:
ret, frame = cap.read()
if not ret:
break
# Update tracker
success, bbox = tracker.update(frame)
if success:
# Draw bounding box
x, y, w, h = map(int, bbox)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(frame, 'Tracking', (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
else:
cv2.putText(frame, 'Lost', (50, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)
cv2.imshow('Tracking', frame)
if cv2.waitKey(30) & 0xFF == 27: # ESC key to exit
break
cap.release()
cv2.destroyAllWindows()