1+ # Usage
2+ # python scripts/meanshift_tracking.py -u 'rtsp://admin:instar@192.168.2.19/livestream/13'
3+ import cv2
4+ from matplotlib import pyplot as plt
5+ import argparse
6+ # from imutils import resize
7+ from imutils .video import VideoStream
8+
9+ # Parse the arguments
10+ ap = argparse .ArgumentParser ()
11+ ap .add_argument ("-u" , "--url" , help = "RTSP streaming URL" , default = "rtsp://admin:instar@192.168.2.19/livestream/13" )
12+ args = vars (ap .parse_args ())
13+
14+ # get video stream from IP camera
15+ print ("[INFO] starting video stream" )
16+ vs = VideoStream (args ["url" ]).start ()
17+
18+ # first frame from stream
19+ frame = vs .read ()
20+ # optional - resize image if source too high res
21+ # frame = resize(frame, width=1280)
22+ # select region of interest
23+ bbox = cv2 .selectROI (frame )
24+ x , y , w , h = bbox
25+ track_window = (x , y , w , h )
26+
27+ # define area of bounding box as area of interest
28+ roi = frame [y :y + h , x :x + w ]
29+ # [DEBUG] display region of interest
30+ # cv2.imshow("ROI", roi)
31+ # if cv2.waitKey(1) & 0xFF == ord('q'):
32+ # break
33+
34+ # convert frame to HSV colour space
35+ hsv_roi = cv2 .cvtColor (roi , cv2 .COLOR_BGR2HSV )
36+ # get histogram for [0] blue, [1] green, [2] red channel
37+ # https://docs.opencv.org/4.x/d1/db7/tutorial_py_histogram_begins.html
38+ roi_hist = cv2 .calcHist ([hsv_roi ], [0 ], None , [180 ], [0 , 180 ])
39+ # [DEBUG] display region of interest histogram
40+ # plt.hist(roi.ravel(), 256, [0, 256])
41+ # plt.show()
42+ # if cv2.waitKey(1) & 0xFF == ord('q'):
43+ # break
44+
45+ # convert hist values 0-180 to a range between 0-1
46+ roi_hist = cv2 .normalize (roi_hist , roi_hist , 0 , 255 , cv2 .NORM_MINMAX )
47+ # set up the termination criteria, either 10 iteration or move by at least 1 pt
48+ parameter = (cv2 .TERM_CRITERIA_EPS | cv2 .TERM_CRITERIA_COUNT , 10 , 1 )
49+
50+ # now loop through the rest of avail frames
51+ # and use meanshift to track defined roi
52+ while True :
53+ # get next frame
54+ frame = vs .read ()
55+ if True :
56+ # convert to hsv
57+ hsv = cv2 .cvtColor (frame , cv2 .COLOR_BGR2HSV )
58+ # compare blue channel of current with roi histogram
59+ # https://docs.opencv.org/3.4.15/da/d7f/tutorial_back_projection.html
60+ dst = cv2 .calcBackProject ([hsv ], [0 ], roi_hist , [0 , 180 ], 1 )
61+ # call meanshift() to find match of histogram in current frame
62+ # and get the new coordinates
63+ ok , track_window = cv2 .meanShift (dst , (x , y , w , h ), parameter )
64+ if not ok :
65+ print ('[WARNING] track lost' )
66+ # now update the roi coordinates to new values
67+ x , y , w , h = track_window
68+ cv2 .rectangle (frame , (x , y ), (x + w , y + h ), (0 , 255 , 255 ), 5 )
69+ # display track
70+ cv2 .imshow ("Meanshift Track" , frame )
71+ if cv2 .waitKey (1 ) & 0xFF == ord ('q' ):
72+ break
73+ else :
74+ break
75+
76+
77+ cv2 .destroyAllWindows ()
0 commit comments