-
Notifications
You must be signed in to change notification settings - Fork 0
/
vision detection and tracking with track ids
396 lines (307 loc) · 16.7 KB
/
vision detection and tracking with track ids
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
vision detection and tracking with track ids.py
import cv2
from ultralytics import YOLO
from collections import defaultdict
import numpy as np
import pandas as pd
import time
from datetime import datetime
import os
import socket
HOST = "192.168.137.5"
PORT = 22400
""" TODO / Improvements
- Clean up code (clear comments and use functions, check for using less if statements etc)
- Make version without image and excel save (speed)
- apply crop on only the belt (changes coordinates)
- try out downsampling frames
- use GPU
- Try out object tracking with speed estimation for noise reduction
"""
def vision_test():
#easy acces variables for testing
global last_coordinates
last_coordinates = False
sent_coordinates = False
i = 1 #track_id ==1 then i+1
j = 1 #coordinates send then j+1
virtual_line = 300
conveyorwait = 800
confidence = 0.80
track_time = 1 #only higher when using track_history information. otherwise not necessary to store old data
consecutive_missing_threshold = 4 #threshold for consecutive frames that mis a detection for deleting the track history
track_history = defaultdict(lambda: []) # Store the track history, create a defaultdict with default value as an empty list
#lists for storing data and exporting to excel
i_list = [1]
j_list = [1]
#mid_x_list = [0]
#mid_y_list = [0]
yrev_wereld_list = [1]
xrev_wereld_list = [1]
elapsed_times = [0]
belt_off_list = [0]
id_track_list = [0]
start_time = time.time()
current_time = datetime.now().strftime("%d-%H-%M")
#output directory for storing the frame files in detection with a name of the current time
output_directory_frames = f'detection/{current_time}'
os.makedirs(output_directory_frames, exist_ok=True) # Create the output directory if it doesn't exist
#output_directory_excel = f'detection'
frame_count=0
# Load the YOLOv8 model
#model =YOLO('runs/detect/yolov8n_towel_detection_tracking/weights/best.pt', 'v8')
model =YOLO('runs/detect/yolov8n_toweltrainingV43/weights/best.pt', 'v8')
#model =YOLO('runs/detect/yolov8n_toweltrainingV733/weights/best.pt', 'v8')
#set colors
blue = (255,0,0)
green = (0,255,0)
red = (0,0,255)
pink = (92,11,227)
orange = (5,94,255)
purple = (255,25,162)
black = (0,0,0)
white = (255,255,255)
grey = (200,200,200)
thickness1 = 1
thickness2 = 2
size1 = 0.7
size2 = 0.7
d1 = 4
font1 = cv2.FONT_HERSHEY_SIMPLEX
font2 = cv2.FONT_HERSHEY_SIMPLEX
#set pixel and world coordinates
RW_X = 400
RW_Y = 480
pixel_X = 214
pixel_Y = 255
pix_RW_X = (RW_X/pixel_X) #1 pixel naar real world coordinates
pix_RW_Y = (RW_Y/pixel_Y)
x_C,y_C = 248,128 #nulpunt
# Open the video file
cap = cv2.VideoCapture(2)
# Loop through the video frames
while cap.isOpened() and last_coordinates == False:
ret, frame_original = cap.read()
#frame_original = frame_original[110:365,0:650]
if ret:
# Run YOLOv8 model
#frame_original = frame_original[:, :-80, :]
results = model.track(frame_original, conf=confidence, persist=True)
# Get the boxes and track IDs
boxes = results[0].boxes.xywh.cpu() #extract bounding boxex of the detected objects
if results[0].boxes.id is not None:
track_ids = results[0].boxes.id.int().cpu().tolist() #all track_ids of the objects that are in the current frame
else:
track_ids = [] #create empty list for a new track id
frame_original = results[0].plot() # Visualize the results on the frame_original
"""
# Remove track IDs that are not present in the last X frames to compensate for noise
for existing_track_id in list(track_history.keys()): #loops trhough the existing track_ids stored in track_history (existing_track_id = key from dictionary)
if existing_track_id not in track_ids:
if 'consecutive_missing_count' not in track_history[existing_track_id]:
track_history[existing_track_id]['consecutive_missing_count'] = 1
else:
track_history[existing_track_id]['consecutive_missing_count'] +=1
if track_history[existing_track_id]['consecutive_missing_count'] >= consecutive_missing_threshold:
del track_history[existing_track_id]
else:
#reset the missing count. Object is in the current frame
if 'consecutive_missing_count' in track_history[existing_track_id]:
del track_history[existing_track_id]['consecutive_missing_count']
"""
# Plot the tracks
for box, track_id in zip(boxes, track_ids):
x, y, w, h = box
track = track_history[track_id]
print(track_id)
track.append((float(x), float(y))) # x, y center point
if len(track) > track_time: # retain 90 tracks for 90 frames
track.pop(0)
# Draw the tracking lines
points = np.hstack(track).astype(np.int32).reshape((-1, 1, 2))
cv2.polylines(frame_original, [points], isClosed=False, color=(green), thickness=2)
# Calculate midpoint
midpoint_x = int(x)
midpoint_y = int(y)
#print("mid x : " ,midpoint_x)
#print("mid y : ", midpoint_y)
#midpoint
#x_C,y_C = 248,128
x_P, y_P = midpoint_x, midpoint_y
cv2.circle(frame_original,(x_C,y_C),10,(blue),3)
cv2.circle(frame_original,(x_P,y_P),6,(red),2)
#relatieve beweging in pixels
xrev_pixel = x_P - x_C
yrev_pixel = y_P - y_C
cv2.line(frame_original, (x_C,y_C), (x_P,y_P), (green),3)
#relatieve beweging in real world
xrev_wereld = int(xrev_pixel*pix_RW_X)
yrev_wereld = int(yrev_pixel*pix_RW_Y)
xrev_wereld = str(xrev_wereld)
yrev_wereld = str(yrev_wereld)
elapsed_time = time.time() - start_time
"""
#append variables to list (before sending coordinates and virtual line) NOTE THIS WILL PRINT EVERY FRAME WITH A DETECTION IN IT
i_list.append(i)
i_list.append(j)
mid_x_list.append(midpoint_x)
mid_y_list.append(midpoint_y)
elapsed_times.append(elapsed_time)
belt_off_list.append(belt_off)
"""
print(" i ", i)
print(" track_id ", track_id)
belt_off = str(-5)
if midpoint_x >= virtual_line:
#stop_conveyor = True
if track_id==i:
# Send coordinates only if they haven't been sent before
rev_move = f'{belt_off}' # Combine DY, DX, and belt_off values
client_socket.sendall(rev_move.encode("utf-8"))
sent_coordinates = True # Set the flag to True after sending coordinates#stop_conveyor = True
belt_off = 1
i +=1
#"""
#append variables after passing line and turning belt of. Coordinates not updated or send yet
i_list.append(i)
j_list.append(j)
#mid_x_list.append(midpoint_x)
#mid_y_list.append(midpoint_y)
elapsed_times.append(elapsed_time)
belt_off_list.append(belt_off)
id_track_list.append(track_id)
yrev_wereld_list.append(yrev_wereld)
xrev_wereld_list.append(xrev_wereld)
#"""
belt_off = 0
cv2.waitKey(conveyorwait)
while sent_coordinates == True:
ret, frame_original = cap.read()
if ret:
# Run YOLOv8 model
#frame_original = frame_original[110:365,0:650]
results = model.track(frame_original, conf=confidence, persist=False)
# Get the boxes and track IDs
boxes = results[0].boxes.xywh.cpu()
if results[0].boxes.id is not None:
track_ids = results[0].boxes.id.int().cpu().tolist()
sent_coordinates==False
else:
track_ids = []
frame_original = results[0].plot() # Visualize the results on the frame_original
# Plot the tracks
for box, track_id in zip(boxes, track_ids):
x, y, w, h = box
track = track_history[track_id]
print(track_id)
track.append((float(x), float(y))) # x, y center point
if len(track) > track_time: # retain 90 tracks for 90 frames
track.pop(0)
# Draw the tracking lines
#points = np.hstack(track).astype(np.int32).reshape((-1, 1, 2))
#cv2.polylines(frame_original, [points], isClosed=False, color=(green), thickness=2)
# Calculate midpoint
midpoint_x = int(x)
midpoint_y = int(y)
#midpoint
#x_C,y_C = 248,128
x_P, y_P = midpoint_x, midpoint_y
cv2.circle(frame_original,(x_C,y_C),10,(blue),3)
cv2.circle(frame_original,(x_P,y_P),6,(red),2)
#relatieve beweging in pixels
xrev_pixel = x_P - x_C
yrev_pixel = y_P - y_C
cv2.line(frame_original, (x_C,y_C), (x_P,y_P), (green),3)
#relatieve beweging in real world
xrev_wereld = int(xrev_pixel*pix_RW_X)
yrev_wereld = int(yrev_pixel*pix_RW_Y)
xrev_wereld = str(xrev_wereld)
yrev_wereld = str(yrev_wereld)
a = f'{yrev_wereld},{xrev_wereld}' # Combine DY, DX, and belt_off values
client_socket.sendall(a.encode("utf-8"))
j +=1
#"""
#append variables after sending new coordinates
i_list.append(i)
j_list.append(j)
#mid_x_list.append(midpoint_x)
#mid_y_list.append(midpoint_y)
elapsed_times.append(elapsed_time)
belt_off_list.append(belt_off)
id_track_list.append(track_id)
yrev_wereld_list.append(yrev_wereld)
xrev_wereld_list.append(xrev_wereld)
#"""
#"""
frame_count +=1
# Save the frame to the specified directory
frame_filename = f'{output_directory_frames}/TOWEL_COORDINATES_{frame_count}.png'
cv2.imwrite(frame_filename, frame_original)
print(f"Frame {frame_count} saved to {frame_filename}")
#"""
last_coordinates = True
break
break
break
cv2.waitKey(200)
break
cv2.waitKey(1)
break
#Drawing lines and circles
cv2.arrowedLine(frame_original, (x_C,y_C), (x_P,y_P), (green),3)
cv2.circle(frame_original, (midpoint_x, midpoint_y), d1, (red), -1)
cv2.circle(frame_original,(x_C,y_C),d1,(red),-1)
cv2.circle(frame_original,(x_P,y_P),d1,(red),2)
cv2.line(frame_original, (virtual_line,0),(virtual_line,480),(pink), 2)
#Put text on frame_original
textC = f"C: ({x_C}, {y_C})"
cv2.putText(frame_original, textC, (x_C+30, y_C), font1, size2, (red), thickness2, cv2.LINE_AA)
textP = f"P: ({x_P}, {y_P})"
cv2.putText(frame_original, textP, (x_P+30, y_P), font1, size2, (red), thickness2, cv2.LINE_AA)
cv2.rectangle(frame_original,(0,0),(240,90), (grey),-1)
text = f"Midpoint: ({midpoint_x},{midpoint_y})"
cv2.putText(frame_original, text, (10, 20), font1, size1, (black), thickness1, cv2.LINE_AA)
text = f"Move: ({yrev_wereld},{xrev_wereld})"
cv2.putText(frame_original, text, (10, 50), font1, size1, (black), thickness1, cv2.LINE_AA)
text = f"ID, i: ({track_id}, {i})"
cv2.putText(frame_original, text, (10, 80), font1, size1, (black), thickness1, cv2.LINE_AA)
# Display theframe
cv2.imshow("YOLOv8 Tracking", frame_original)
# Break the loop if 'q' is pressed
if cv2.waitKey(1) & 0xFF == ord("q"):
break
else:
#Break the loop if the end of the video is reached
break
cap.release()
cv2.destroyAllWindows()
#"""
data = {
"i" : i_list,
"j" : j_list,
"yrev_wereld_list" : yrev_wereld_list,
"xrev_wereld_list" : xrev_wereld_list,
"time" : elapsed_times,
"belt sent" : belt_off_list,
"id track" : id_track_list
}
output_directory = 'detection'
output_file_name = f'{output_directory}/{current_time}.xlsx'
df = pd.DataFrame(data)
df.to_excel(output_file_name, index=False)
print(f"DataFrame saved to {output_file_name}")
#"""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:
client_socket.connect((HOST, PORT))
message_to_server = "Hello world, this is spyder" #storing data (str) in a variable
client_socket.sendall(message_to_server.encode("utf-8"))
while True:
print("Waiting for command...")
data = client_socket.recv(1024) #receiving data from server
server_response = data.decode("utf-8") #storing data (str) in a variable
print("Server response:", server_response)
if server_response == 'exit':
print('exiting...')
break
elif server_response == 'vision_test()':
vision_test()