goturnTracker.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. # Copyright 2018 Satya Mallick (LearnOpenCV.com)
  2. # Import modules
  3. import cv2, sys, os
  4. if not (os.path.isfile('goturn.caffemodel') and os.path.isfile('goturn.prototxt')):
  5. errorMsg = '''
  6. Could not find GOTURN model in current directory.
  7. Please ensure goturn.caffemodel and goturn.prototxt are in the current directory
  8. '''
  9. print(errorMsg)
  10. sys.exit()
  11. # Create tracker
  12. tracker = cv2.TrackerGOTURN_create()
  13. # Read video
  14. video = cv2.VideoCapture("chaplin.mp4")
  15. # Exit if video not opened
  16. if not video.isOpened():
  17. print("Could not open video")
  18. sys.exit()
  19. # Read first frame
  20. ok,frame = video.read()
  21. if not ok:
  22. print("Cannot read video file")
  23. sys.exit()
  24. # Define a bounding box
  25. bbox = (276, 23, 86, 320)
  26. # Uncomment the line below to select a different bounding box
  27. #bbox = cv2.selectROI(frame, False)
  28. # Initialize tracker with first frame and bounding box
  29. ok = tracker.init(frame,bbox)
  30. while True:
  31. # Read a new frame
  32. ok, frame = video.read()
  33. if not ok:
  34. break
  35. # Start timer
  36. timer = cv2.getTickCount()
  37. # Update tracker
  38. ok, bbox = tracker.update(frame)
  39. # Calculate Frames per second (FPS)
  40. fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer);
  41. # Draw bounding box
  42. if ok:
  43. # Tracking success
  44. p1 = (int(bbox[0]), int(bbox[1]))
  45. p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
  46. cv2.rectangle(frame, p1, p2, (255,0,0), 2, 1)
  47. else :
  48. # Tracking failure
  49. cv2.putText(frame, "Tracking failure detected", (100,80), cv2.FONT_HERSHEY_SIMPLEX, 0.75,(0,0,255),2)
  50. # Display tracker type on frame
  51. cv2.putText(frame, "GOTURN Tracker", (100,20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50),2);
  52. # Display FPS on frame
  53. cv2.putText(frame, "FPS : " + str(int(fps)), (100,50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50), 2);
  54. # Display result
  55. cv2.imshow("Tracking", frame)
  56. # Exit if ESC pressed
  57. k = cv2.waitKey(1) & 0xff
  58. if k == 27:
  59. break