e.g.: OpenCV Tracking selected object (ROI) – TrackerKCF – Realtime Position Data for Robot Vision

  
import cv2

tracker = cv2.TrackerKCF_create()
video = cv2.VideoCapture(0) # 0,1 .. as per available cameras

while True:
    k,frame = video.read()
    cv2.imshow("Tracking",frame)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break
bbox = cv2.selectROI(frame, False)

ok = tracker.init(frame, bbox)
cv2.destroyWindow("ROI selector")

while True:
    ok, frame = video.read()
    ok, bbox = tracker.update(frame)

    if ok:
        p1 = (int(bbox[0]), int(bbox[1]))
        p2 = (int(bbox[0] + bbox[2]),
              int(bbox[1] + bbox[3]))
        cv2.rectangle(frame, p1, p2, (0,0,255), 2, 2)
        
        print("p1 data: "+str(p1))
        print("p2 data: "+str(p2))

    cv2.imshow("Tracking", frame)
    k = cv2.waitKey(1) & 0xff
    if k == 27 : break

Step 1: Run the code

Step 2: Once Camera visible, click Esc button on Keyboard.

Step 3: Select Region of Interest (ROI)

Step 4: Press Esc

Step 5: Move subject to see Tracking in action.

Enjoy!

5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Next Post

Robot Serving Beer

Tue Apr 6 , 2021

0

0
Would love your thoughts, please comment.x
()
x