#importing cv2 and system package
import cv2
import sys
#So how do you ensure that your code will work no matter which version of OpenCV your production environment is using
# Extract major, minor, and subminor version numbers
(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')
#Every Python module has it’s __name__ defined and if this is ‘__main__’, it implies that the module is being run standalone
#by the user and we can do corresponding appropriate actions.
if __name__ == '__main__' :
# Set up tracker.
tracker_type = 'TLD'
if int(minor_ver) < 3:
tracker = cv2.Tracker_create(tracker_type)
else:
if tracker_type == 'TLD':
tracker = cv2.TrackerTLD_create()
# Read video
video = cv2.VideoCapture("./videos/chaplin.mp4")
# Exit if video not opened.
if not video.isOpened():
print("Could not open video")
sys.exit()
# Read first frame.
ok, frame = video.read()
if not ok:
print('Cannot read video file')
sys.exit()
#rectangular region of interest (ROI)
#Let’s start with a sample code. It allows you to select a rectangle in an image,
#crop the rectangular region and finally display the cropped image.
bbox = cv2.selectROI(frame, False)
# Initialize tracker with first frame and bounding box
ok = tracker.init(frame, bbox)
file=open("Coordinate.txt","w")
while True:
# Read a new frame
ok, frame = video.read()
if not ok:
break
# Start timer
timer = cv2.getTickCount()
# Update tracker
ok, bbox = tracker.update(frame)
# Calculate Frames per second (FPS)
fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer);
frame_count = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
# Draw bounding box
if ok:
# Tracking success
p1 = (int(bbox[0]), int(bbox[1]))
p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
cv2.rectangle(frame, p1, p2, (255,0,0), 2, 1)
else :
# Tracking failure
cv2.putText(frame, "Tracking failure detected", (100,80), cv2.FONT_HERSHEY_SIMPLEX, 0.75,(0,0,255),2)
#cv2.putText(img, text, position, font, fontScale, color, thickness, lineType, bottomLeftOrigin)
# Display tracker type on frame
cv2.putText(frame, tracker_type + " Tracker", (100,20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50),2);
timer=(cv2.getTickCount()-timer)/cv2.getTickFrequency()
#Display X and Y Coordinate
cv2.putText(frame,"X and Y Coordinate "+str(p1)+" and "+str(p2), (100,70), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50),2);
file.write(str(timer)+" :: UpperLeft(x,y) and BottomRight(x,y) "+str(p1)+" and "+str(p2)+"\n")
# Display FPS on frame
cv2.putText(frame, "FPS : " + str(int(fps)), (100,50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50), 2);
# Display result
cv2.imshow("Tracking", frame)
# Exit if ESC pressed
k = cv2.waitKey(1) & 0xff
if k == 27 :
file.close()
break
Credit : Github
Note : Code has taken from Github and modified according to need .
No comments:
Post a Comment