Nonsense do not say, look at the code comments can be.
Required: OpenCV 3+contrib, Python 3
# Introduce required module import CV2 Import sys # mouse frame selection for display mouse trajectory selection = none # box select Start Drag_start = none # Box Select completion area that tracks target Track_window = N One # trace start flag Track_start = False # Create KCF Tracker tracker = Cv2. Trackerkcf_create () # Mouse response function def onmouse (event, x, Y, Flags, param): Global selection, Drag_start, Track_window, tra Ck_start # The left mouse button press if event = = Cv2. Event_lbuttondown:drag_start = (x, y) Track_window = None # start dragging if drag_start:xmin = mi N (x, drag_start[0]) ymin = min (y, drag_start[1]) Xmax = max (x, drag_start[0)) Ymax = Max (Y, drag_s TART[1] Selection = (xmin, ymin, Xmax, ymax) # The left mouse button bounces up if event = = Cv2. Event_lbuttonup:drag_start = None Selection = None Track_window = (xmin, ymin, Xmax-xmin, ymax
-ymin) if Track_window and track_window[2] > 0 and track_window[3] > 0:track_start = True # The Tracker initializes the Tracker.init (frame, Track_window) with the frame and box selection as the left mouse button.
# Read video/webcam = Cv2. Videocapture (0) # video = Cv2. Videocapture ("Test2.mp4") # naming window, the second parameter indicates that the window can be scaled Cv2.namedwindow (' Kcftracker ', Cv2.
Window_normal) # for Windows Bound mouse response function Onmouse cv2.setmousecallback (' Kcftracker ', onmouse) # If the camera is not opened correctly, exit if not video.isopened ():
Print (' could not open ") sys.exit () while True: # reads current frame OK, frame = Video.read () If not OK: Break # with a rectangular marker mouse box Select Area if selection:x0, y0, x1, y1 = Selection Cv2.rectangle (frame, (x0, y0), (x1, y1), (255, 0, 0), 2, 1) # function execution Start timer = Cv2.gettickcount () # Update tracker gets latest target area TRACK_OK = None if tr ACK_START:TRACK_OK, bbox = Tracker.update (frame) # compute fps fps = cv2.gettickfrequency ()/(Cv2.gettickcoun T ()-timer) # Draw the target newest boundary area # If the trace succeeds if track_ok:p1 = (int (bbox[0]), int (bbox[1]) P2 = (int (b Box[0] + bbox[2]), int (bbox[1] + bbox[3)) Cv2.rectangle (frame, p1, p2, (255, 0, 0), 2, 1) elif not Track_star
T: Cv2.puttext (Frame, "No tracking target selected", (MB), Cv2. Font_hershey_simplex, 0.75, (0, 0, 255), 2) elif not Track_ok:cv2.putText (frame, "Tracking failure detected", (a), Cv2. Font_hershey_simplex, 0.75, (0, 0, 255), 2) # Displays prompt information Cv2.puttext (frame, "KCF Tracker", (MB), Cv2. Font_hershey_simplex, 0.75, (M, 170, 2) Cv2.puttext (frame, "FPS:" + str (int (FPS)), Cv2. Font_hershey_simplex, 0.75, (50, 170, 50), 2) # Display results cv2.imshow ("Kcftracker", frame) # Press ESC to exit K = Cv2.wa
Itkey (1) & 0xFF if k = = 27:break video.release () cv2.destroyallwindows ()