1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
|
import argparse
import cv2 as cv from imutils.video import FPS
OPENCV_OBJECT_TRACKERS = { "csrt": cv.TrackerCSRT_create, "kcf": cv.TrackerKCF_create, "mil": cv.TrackerMIL_create, }
def tracking(video_path=None, tracker_name="kcf"): if video_path is None: video_path = 0 tracker = OPENCV_OBJECT_TRACKERS[tracker_name]() initBB = None fps = None window_name = "real-time" cap = cv.VideoCapture(video_path) is_open = cap.isOpened() while is_open: return_value, frame = cap.read() H, W = frame.shape[:2] if initBB is not None: success, box = tracker.update(frame) if success: x, y, w, h = [int(v) for v in box] cv.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) fps.update() fps.stop() info = [('Tracker', tracker_name), ('Success', "Yes" if success else 'No'), ("FPS", "{:.2f}".format(fps.fps()))]
for i, (k, v) in enumerate(info): text = "{}: {}".format(k, v) cv.putText(frame, text, (10, H - ((i * 20) + 20)), cv.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
if return_value: cv.namedWindow(window_name, cv.WINDOW_NORMAL) cv.imshow(window_name, frame)
k = cv.waitKey(1) & 0xff if k == ord('s'): initBB = cv.selectROI(window_name, frame, fromCenter=False, showCrosshair=True) tracker.init(frame, initBB) fps = FPS().start() elif k == ord('q'): break
cap.release() cv.destroyAllWindows()
if __name__ == '__main__': ap = argparse.ArgumentParser() ap.add_argument("-v", "--video", type=str, default=None, help="path to input video file") ap.add_argument("-t", "--tracker", type=str, default='kcf', help="OpenCV object tracker name") args = vars(ap.parse_args())
tracking(args["video"], args["tracker"])
|