|
| 1 | +from imutils.video import VideoStream |
| 2 | +import imutils |
| 3 | +import time |
| 4 | +import cv2 |
| 5 | +import numpy as np |
| 6 | + |
| 7 | + |
| 8 | +def main(): |
| 9 | + |
| 10 | + # initialize a dictionary that maps strings to their corresponding OpenCV object tracker implementations |
| 11 | + OPENCV_OBJECT_TRACKERS = { |
| 12 | + #"csrt": cv2.TrackerCSRT_create, |
| 13 | + "kcf": cv2.TrackerKCF_create, |
| 14 | + "boosting": cv2.TrackerBoosting_create, |
| 15 | + "mil": cv2.TrackerMIL_create, |
| 16 | + "tld": cv2.TrackerTLD_create, |
| 17 | + "medianflow": cv2.TrackerMedianFlow_create |
| 18 | + #"mosse": cv2.TrackerMOSSE_create |
| 19 | + } |
| 20 | + |
| 21 | + # initialize OpenCV's special multi-object tracker |
| 22 | + trackers = cv2.MultiTracker_create() |
| 23 | + |
| 24 | + video_path = 'videos/nascar.mp4' |
| 25 | + cap = cv2.VideoCapture(video_path) |
| 26 | + |
| 27 | + if cap.isOpened(): |
| 28 | + ret, frame = cap.read() |
| 29 | + else: |
| 30 | + ret = False |
| 31 | + |
| 32 | + |
| 33 | + while ret: |
| 34 | + |
| 35 | + ret, frame = cap.read() |
| 36 | + |
| 37 | + #frame = cv2.resize(frame, (700, 700)) |
| 38 | + |
| 39 | + frame = np.copy(frame) |
| 40 | + |
| 41 | + print(frame.dtype) # output will be : uint8 |
| 42 | + print(frame.shape) |
| 43 | + |
| 44 | + # frame = imutils.resize(frame, width=600) |
| 45 | + |
| 46 | + # Get bounding box coordinates (if any) for each object that is being tracked |
| 47 | + (success, boxes) = trackers.update(frame) |
| 48 | + |
| 49 | + # loop over the bounding boxes and draw then on the frame |
| 50 | + for box in boxes: |
| 51 | + (x, y, w, h) = [int(i) for i in box] |
| 52 | + cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) |
| 53 | + |
| 54 | + |
| 55 | + cv2.imshow("Random Object Tracking", frame) |
| 56 | + |
| 57 | + key = cv2.waitKey(1) & 0xFF |
| 58 | + |
| 59 | + # if the 's' key is selected, we are going to "select" a bounding box to track |
| 60 | + if key == ord("s"): |
| 61 | + # select the bounding box of the object we want to track (make sure you press ENTER or SPACE after selecting the ROI) |
| 62 | + box = cv2.selectROI("Frame", frame, fromCenter=False, showCrosshair=True) |
| 63 | + |
| 64 | + # create a new object tracker for the bounding box and add it to our multi-object tracker |
| 65 | + tracker = OPENCV_OBJECT_TRACKERS["kcf"]() |
| 66 | + trackers.add(tracker, frame, box) |
| 67 | + |
| 68 | + # if the `q` key was pressed, break from the loop |
| 69 | + elif key == ord("q"): |
| 70 | + break |
| 71 | + |
| 72 | + else: |
| 73 | + cap.release() |
| 74 | + |
| 75 | + |
| 76 | + # close all windows |
| 77 | + cap.release() |
| 78 | + cv2.destroyAllWindows() |
| 79 | + |
| 80 | + |
| 81 | +if __name__ == '__main__': |
| 82 | + main() |
0 commit comments