Replace Object_Tracker2.py

parent e7a3e9ba
#REFERENCE MATERIAL
#https://livecodestream.dev/post/object-tracking-with-opencv/
import cv2 import cv2
import sys import sys
import csv import csv
import pandas as pd
(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.') (major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')
frameNo = 0
if __name__ == '__main__' : if __name__ == '__main__' :
# Set up tracker.
# Instead of MIL, you can also use # Set up tracker
tracker_types = ['BOOSTING', 'MIL','KCF', 'TLD', 'MEDIANFLOW', 'GOTURN', 'MOSSE', 'CSRT'] tracker_types = ['BOOSTING', 'MIL','KCF', 'TLD', 'MEDIANFLOW', 'GOTURN', 'MOSSE', 'CSRT']
tracker_type = tracker_types[7] tracker_type = tracker_types[7]
if int(minor_ver) < 3: if int(minor_ver) < 3:
tracker = cv2.Tracker_create(tracker_type) tracker = cv2.Tracker_create(tracker_type)
else: else:
if tracker_type == 'BOOSTING': if tracker_type == 'BOOSTING':
tracker = cv2.TrackerBoosting_create() tracker = cv2.TrackerBoosting_create()
if tracker_type == 'MIL': elif tracker_type == 'MIL':
tracker = cv2.TrackerMIL_create() tracker = cv2.TrackerMIL_create()
if tracker_type == 'KCF': elif tracker_type == 'KCF':
tracker = cv2.TrackerKCF_create() tracker = cv2.TrackerKCF_create()
if tracker_type == 'TLD': elif tracker_type == 'TLD':
tracker = cv2.TrackerTLD_create() tracker = cv2.TrackerTLD_create()
if tracker_type == 'MEDIANFLOW': elif tracker_type == 'MEDIANFLOW':
tracker = cv2.TrackerMedianFlow_create() tracker = cv2.TrackerMedianFlow_create()
if tracker_type == 'GOTURN': elif tracker_type == 'GOTURN':
tracker = cv2.TrackerGOTURN_create() tracker = cv2.TrackerGOTURN_create()
if tracker_type == 'MOSSE': elif tracker_type == 'MOSSE':
tracker = cv2.TrackerMOSSE_create() tracker = cv2.TrackerMOSSE_create()
if tracker_type == "CSRT": elif tracker_type == "CSRT":
tracker = cv2.TrackerCSRT_create() tracker = cv2.TrackerCSRT_create()
# Read video # Read video
video = cv2.VideoCapture("EYEDIAP/EYEDIAP/1_A_FT_M/1_A_FT_M.mov") video = cv2.VideoCapture('EYEDIAP\EYEDIAP\_6_A_FT_M\_6_A_FT_M.mov')
# VIDEO_STREAM = 'eyediap1.mov'
VIDEO_STREAM_OUT = 'output_eyediap1_ot2.mp4'
fourcc = cv2.VideoWriter_fourcc(*'XVID')
# video = cv2.VideoCapture(VIDEO_STREAM)
ok, frame = video.read()
# frame = cv2.resize(frame, (640,360), interpolation=cv2.INTER_AREA) #original
# frame = cv2.resize(frame, (640,480), interpolation=cv2.INTER_AREA) #edited to resize
# frame = cv2.resize(frame, (1120,790), interpolation=cv2.INTER_AREA) #full screen size
writer = cv2.VideoWriter(VIDEO_STREAM_OUT, fourcc, 30, (frame.shape[1],frame.shape[0]), True)
# 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()
# Define an initial bounding box
#bbox = (287, 23, 86, 320)
# Uncomment the line below to select a different bounding box
bbox = cv2.selectROI(frame, False)
# Initialize tracker with first frame and bounding box
ok = tracker.init(frame, bbox)
print(frame.shape)
#Writing data to the csv file
with open('1_A_FT_M.csv', mode='w') as object_track_file:
OT_writer = csv.writer(object_track_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
OT_writer.writerow(['Frame_number','x_displacement','y_displacement', 'Tracker_x1', 'Tracker_y1', 'Tracker_x2', 'Tracker_y2'])
while True:
#incrementing the frame count
frameNo = frameNo + 1
# 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)
# 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]))
x1 = int(bbox[0])
y1 = int(bbox[1])
x2 = int(bbox[0] + bbox[2])
y2 = int(bbox[1] + bbox[3])
x1y1 = x1,y1
x2y2 = x2,y2
cv2.rectangle(frame, p1, p2, (255,0,0), 2, 1)
#centroid Calculation
avgX = (p1[0]+p2[0])/2
avgY = (p1[1]+p2[1])/2
print("Frame No : " + str(int(frameNo)))
print("FPS : " + str(int(fps)),"----", p1, " , ", p2)
print("X displacement = ", avgX)
print("Y displacement = ", avgY)
# print('x1y1:',x1y1, '.....', 'x2y2:', x2y2)
print("-----------------------------------------------")
# Writing data to the csv file
OT_writer.writerow([frameNo, avgX, avgY, x1, y1, x2, y2])
else :
# Tracking failure
cv2.putText(frame, "Tracking failure detected", (100,80), cv2.FONT_HERSHEY_SIMPLEX, 0.75,(0,0,255),2)
# Display tracker type on frame
cv2.putText(frame, tracker_type + " Tracker", (100,20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50),2);
# cv2.putText(frameNo, "FRAME No : " + str(int(frameNo)), (100,50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50), 2);
# 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 # Exit if video not opened.
k = cv2.waitKey(1) & 0xff if not video.isOpened():
if k == 27 : break print("Could not open video")
sys.exit()
# Read first frame.
ok, frame = video.read()
if not ok:
print ('Cannot read video file')
sys.exit()
# Define an initial bounding box
bbox = (287, 23, 86, 320)
# Uncomment the line below to select a different bounding box
bbox = cv2.selectROI(frame, False)
# Initialize tracker with first frame and bounding box
ok = tracker.init(frame, bbox)
# Defining arrays to store values
df_frame, df_centerX, df_centerY, df_x1, df_y1, df_x2, df_y2 = [],[],[],[],[],[],[]
frameNo = 0
cv2.destroyAllWindows() while True:
writer.release() # Frame count
frameNo += 1
# 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);
# 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]))
x1 = int(bbox[0])
y1 = int(bbox[1])
x2 = int(bbox[0] + bbox[2])
y2 = int(bbox[1] + bbox[3])
x1y1 = x1,y1
x2y2 = x2,y2
#centroid Calculation
avgX = (p1[0]+p2[0])/2
avgY = (p1[1]+p2[1])/2
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)
#Initializing values
avgX = 0
avgY = 0
x1 = 0
y1 = 0
x2 = 0
y2 = 0
df_frame.append(frameNo)
df_centerX.append(avgX)
df_centerY.append(avgY)
df_x1.append(x1)
df_y1.append(y1)
df_x2.append(x2)
df_y2.append(y2)
print("Frame No : " + str(int(frameNo)))
print("FPS : " + str(int(fps)),"----", p1, " , ", p2)
print("X displacement = ", avgX)
print("Y displacement = ", avgY)
# print('x1y1:',x1y1, '.....', 'x2y2:', x2y2)
print("-----------------------------------------------")
# Display tracker type on frame
cv2.putText(frame, tracker_type + " Tracker", (100,20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50),2);
# 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
if cv2.waitKey(1) & 0xFF == ord('q'): # if press SPACE bar
break
# CSV File generation
df_dict = {'Frame_number': df_frame, 'Tracker_center(x)': df_centerX, 'Tracker_center(y)': df_centerY,'Tracker_x1':df_x1, 'Tracker_y1':df_y1, 'Tracker_x2':df_x2, 'Tracker_y2':df_y2}
df = pd.DataFrame(df_dict)
print(df.head)
df.to_csv("csv_files/Eyediap_csv/Tracker_output_6_A_FT_M.csv", index=False)
video.release()
cv2.destroyAllWindows()
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment