-
Notifications
You must be signed in to change notification settings - Fork 0
/
perception_stack.py
625 lines (508 loc) · 21.3 KB
/
perception_stack.py
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
# Semester Project: Perception Stack for Autonomous Driving
# Maksim Pikovskiy <[email protected]>
import os
import time
import numpy as np
import open3d as o3d
# Print num of clusters per frame and vehicle info per frame
DEBUG_MODE = False
# Save latencies for each frame and average latency
SAVE_LATENCIES = False
# Path to where the Point Cloud frames are stored
path_frames = "dataset/PointClouds"
# Assuming the max height of a normal vehicle is 4.75 meters (with some overhead)
# Normal car: ~ 2 meters
# Normal truck: ~ 4 meters
car_height = 4.75
# Assuming the ground level is at 0 meters
ground_level = 0.005
# Threshold for determining if two vehicles are the same
distance_threshold = np.asarray([2, 2, 2])
def read_and_preprocess(filename):
"""
Read a PCD file and preprocess it for vehicle detection.
Parameters:
- filename: Path to the PCD file.
Returns:
- pcd: Processed point cloud.
"""
# Read point cloud
pcd = o3d.io.read_point_cloud(filename)
# Down sample to increase speed of processing
# pcd = pcd.voxel_down_sample(voxel_size=0.075) # results in more clusters and more false positives
# Alternative for downsampling
# Remove points out possible range for cars and trucks
pcd = pcd.select_by_index(np.where(np.asarray(pcd.points)[:, 2] < car_height)[0])
pcd = pcd.select_by_index(np.where(np.asarray(pcd.points)[:, 2] > ground_level)[0])
# pcd, _ = pcd.remove_statistical_outlier(nb_neighbors=3, std_ratio=2.0)
return pcd
def detect_moving_objects(curr_frame, prev_frame):
"""
Detect moving objects in the current frame using background subtraction.
Parameters:
- curr_frame: Current point cloud frame.
- prev_frame: Previous point cloud frame.
Returns:
- frame_diff: Point cloud containing only the points that have changed.
"""
# Compute distances between points that near each other
dists = curr_frame.compute_point_cloud_distance(prev_frame)
dists = np.asarray(dists)
ind = np.where(dists > 0.0020)[0] # get only distances that are significant
# Get the points that have changed
frame_diff = curr_frame.select_by_index(ind)
frame_diff.estimate_normals()
# Delete points with no 5 neighbors in 2 meter radius
# frame_diff, _ = frame_diff.remove_radius_outlier(nb_points=5, radius=2)
return frame_diff
def get_vehicles(frame):
"""
Get vehicles from a point cloud frame using DBSCAN.
Parameters:
- frame: Point cloud frame.
Returns:
- vehicles: List of clusters representing vehicles.
"""
# Check if there are any points in the frame
if len(frame.points) == 0:
return None
# Cluster the points using DBSCAN with eps of 1.75 and min_points of 3
labels = np.array(frame.cluster_dbscan(eps=1.75, min_points=3))
# Check if there are any clusters generated by DBSCAN
if len(labels) == 0:
return None
vehicles = []
max_label = labels.max() # Get the max label
if DEBUG_MODE:
print(f"\t Point Cloud has {max_label + 1} clusters")
# Iterate through all the clusters and add them to the list of vehicles
for i in range(max_label + 1):
cluster = frame.select_by_index(np.where(labels == i)[0])
vehicles.append(cluster)
return vehicles
def compute_bounding_box(cluster):
"""
Compute the bounding box for a cluster.
Parameters:
- cluster: Cluster representing a vehicle.
Returns:
- bounds: Bounding box coordinates [x_min, y_min, z_min, x_max, y_max, z_max].
"""
# Get the min and max values for each axis of the cluster
bounds = [
np.min(np.asarray(cluster.points)[:, 0]),
np.min(np.asarray(cluster.points)[:, 1]),
np.min(np.asarray(cluster.points)[:, 2]),
np.max(np.asarray(cluster.points)[:, 0]),
np.max(np.asarray(cluster.points)[:, 1]),
np.max(np.asarray(cluster.points)[:, 2]),
]
return bounds
def create_bounding_box(bbox):
"""
Create a line set representing a bounding box.
Parameters:
- bbox: Bounding box coordinates [x_min, y_min, z_min, x_max, y_max, z_max].
Returns:
- line_set: Open3D LineSet representing the bounding box.
"""
# Create a line set representing the bounding box
lines = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
]
# Set the color of the lines to red
colors = [[1, 0, 0] for _ in range(len(lines))]
# Create the line set
line_set = o3d.geometry.LineSet()
# Set the points and lines of the line set
line_set.points = o3d.utility.Vector3dVector(
[
[bbox[0], bbox[1], bbox[2]],
[bbox[3], bbox[1], bbox[2]],
[bbox[3], bbox[4], bbox[2]],
[bbox[0], bbox[4], bbox[2]],
[bbox[0], bbox[1], bbox[5]],
[bbox[3], bbox[1], bbox[5]],
[bbox[3], bbox[4], bbox[5]],
[bbox[0], bbox[4], bbox[5]],
]
)
# Set the lines and colors of the line set
line_set.lines = o3d.utility.Vector2iVector(lines)
line_set.colors = o3d.utility.Vector3dVector(colors)
return line_set
def get_position(bounds):
"""
Get the position of a vehicle. Calculate the center of the bounding box.
Parameters:
- bounds: Bounding box coordinates [x_min, y_min, z_min, x_max, y_max, z_max].
Returns:
- position: Position of the vehicle [x, y, z] (center of bounding box).
"""
# Calculate the center of the bounding box
position = [
(bounds[0] + bounds[3]) / 2,
(bounds[1] + bounds[4]) / 2,
(bounds[2] + bounds[5]) / 2,
]
return position
def calculate_volume(bounds):
"""
Calculate the volume of a bounding box for a vehicle.
Parameters:
- bounds: Bounding box coordinates [x_min, y_min, z_min, x_max, y_max, z_max].
Returns:
- volume: Volume of the bounding box for a vehicle.
"""
# Calculate the length, width, and height of the bounding box
length = abs(bounds[3] - bounds[0])
width = abs(bounds[4] - bounds[1])
height = abs(bounds[5] - bounds[2])
return length * width * height
def save_results(detected_vehicles, frame_number):
"""
Save detected vehicle information to a CSV file.
Parameters:
- detected_vehicles: Information about vehicles detected in the current frame.
- frame_number: Current frame number.
"""
# Create a directory for saving the results
result_dir = "perception_results"
os.makedirs(result_dir, exist_ok=True)
# Create a filename for the CSV file
csv_filename = "frame_{i}.csv".format(i=frame_number)
csv_path = os.path.join(result_dir, csv_filename)
# Extract relevant information for saving
ids = ["vehicle_id"] + [vehicle["id"] for vehicle in detected_vehicles]
position_x = ["position_x"] + [
vehicle["position"][0] for vehicle in detected_vehicles
]
position_y = ["position_y"] + [
vehicle["position"][1] for vehicle in detected_vehicles
]
position_z = ["position_z"] + [
vehicle["position"][2] for vehicle in detected_vehicles
]
mvec_x = ["mvec_x"] + [vehicle["motion_vector"][0] for vehicle in detected_vehicles]
mvec_y = ["mvec_y"] + [vehicle["motion_vector"][1] for vehicle in detected_vehicles]
mvec_z = ["mvec_z"] + [vehicle["motion_vector"][2] for vehicle in detected_vehicles]
bbox_x_min = ["bbox_x_min"] + [
vehicle["bounding_box"][0] for vehicle in detected_vehicles
]
bbox_x_max = ["bbox_x_max"] + [
vehicle["bounding_box"][3] for vehicle in detected_vehicles
]
bbox_y_min = ["bbox_y_min"] + [
vehicle["bounding_box"][1] for vehicle in detected_vehicles
]
bbox_y_max = ["bbox_y_max"] + [
vehicle["bounding_box"][4] for vehicle in detected_vehicles
]
bbox_z_min = ["bbox_z_min"] + [
vehicle["bounding_box"][2] for vehicle in detected_vehicles
]
bbox_z_max = ["bbox_z_max"] + [
vehicle["bounding_box"][5] for vehicle in detected_vehicles
]
# Save the results to a CSV file
np.savetxt(
csv_path,
[
p
for p in zip(
ids,
position_x,
position_y,
position_z,
mvec_x,
mvec_y,
mvec_z,
bbox_x_min,
bbox_x_max,
bbox_y_min,
bbox_y_max,
bbox_z_min,
bbox_z_max,
)
],
delimiter=",",
fmt="%s",
)
def track_vehicles(vehicles, tracked_vehicles):
"""
Track vehicles across frames. Matches the vehicles detected in the current
frame with the vehicles detected in the previous frame. If a match is found,
the vehicle is assigned the same ID as the vehicle in the previous frame. If
no match is found, a new ID is assigned to the vehicle. If there are more than
6 vehicles detected in the current frame, the vehicles with the smallest volume
are removed.
Parameters:
- vehicles: Information about vehicles detected in the current frame.
- tracked_vehicles: Information about vehicles detected in previous frames.
Returns:
- new_vehicles: Information about vehicles detected in the current frame.
"""
# Check if there are any vehicles detected in the current frame
new_vehicles = []
if tracked_vehicles is None or len(tracked_vehicles) == 0:
# Assign IDs to the vehicles of initial frame
for idx, vehicle in enumerate(vehicles):
if len(vehicles) == 6:
break
vehicle["id"] = idx
vehicle["color"] = np.random.rand(3)
new_vehicles.append(vehicle)
else:
# Match vehicles in current frame with vehicles in previous frame
detected_vehicles = []
for vehicle in vehicles:
has_match = False
for veh_track in tracked_vehicles:
# Calculate the distance between the vehicles
distance = abs(
np.asarray(vehicle["position"]) - np.asarray(veh_track["position"])
)
# Check if the distance is less than the threshold
if (
np.all(distance < distance_threshold)
# and veh_track["id"] not in detected_vehicles
):
vehicle["id"] = veh_track["id"]
vehicle["color"] = veh_track["color"]
detected_vehicles.append(veh_track["id"])
new_vehicles.append(vehicle)
has_match = True
break
# If no match is found, assign a new ID to the vehicle
# and add it to the list of new vehicles
if not has_match and len(new_vehicles) <= 6:
vehicle["id"] = len(new_vehicles)
vehicle["color"] = np.random.rand(3)
new_vehicles.append(vehicle)
# Get the vehicles that were not detected in the current frame
undetected_vehicles = [
vehicle
for vehicle in tracked_vehicles
if vehicle["id"] not in detected_vehicles
]
# Update the position and bounding box of the undetected vehicles
# Based on the motion vector (Unreliable due to loss of points in blind spot)
# for undetected_vehicle in undetected_vehicles:
# undetected_vehicle["position"] = np.array(
# undetected_vehicle["position"]
# ) + np.array(undetected_vehicle["motion_vector"])
# undetected_vehicle["bounding_box"][0] += undetected_vehicle[
# "motion_vector"
# ][0]
# undetected_vehicle["bounding_box"][3] += undetected_vehicle[
# "motion_vector"
# ][0]
# undetected_vehicle["bounding_box"][1] += undetected_vehicle[
# "motion_vector"
# ][1]
# undetected_vehicle["bounding_box"][4] += undetected_vehicle[
# "motion_vector"
# ][1]
# undetected_vehicle["bounding_box"][2] += undetected_vehicle[
# "motion_vector"
# ][2]
# undetected_vehicle["bounding_box"][5] += undetected_vehicle[
# "motion_vector"
# ][2]
# new_vehicles.append(undetected_vehicle)
# Add the undetected vehicles to the list of new vehicles
new_vehicles.extend(undetected_vehicles)
# Remove vehicles with small volume if there are more than 6 vehicles
if len(new_vehicles) > 6:
for vehicle in new_vehicles:
if calculate_volume(vehicle["bounding_box"]) < 1.0:
new_vehicles.remove(vehicle)
return new_vehicles
def get_similar_vehicle(vehicles, vehicle_position):
"""
Get a vehicle from a list of vehicles that is similar to the vehicle
with the given position.
Parameters:
- vehicles: List of vehicles.
- vehicle_position: Position of the vehicle to find a match for.
Returns:
- veh: Vehicle that is similar to the vehicle with the given position.
"""
# Match vehicle in current frame with similar vehicle in previous frame
# using the distance between the vehicles' positions
for veh in vehicles:
distance = abs(np.array(vehicle_position) - np.array(veh["position"]))
if np.all(distance < distance_threshold):
return veh
return None
def get_vehicle_infos(vehicles, prev_vehicles_info):
"""
Get information about vehicles detected in the current frame.
Information is id, position, bounding box, and motion vector.
Parameters:
- vehicles: List of clusters representing vehicles.
- prev_vehicles_info: Information about vehicles detected in previous frame.
Returns:
- vehicles_info: Information about vehicles detected in the current frame.
"""
vehicles_info = []
for idx, vehicle in enumerate(vehicles):
# Compute the bounding box and position for the vehicle
bounds = compute_bounding_box(vehicle)
position = get_position(bounds)
# Compute the motion vector for the vehicle
motion_vector = [0, 0, 0]
if prev_vehicles_info is not None:
prev_vehicle = get_similar_vehicle(prev_vehicles_info, position)
if prev_vehicle is not None:
motion_vector = np.array(prev_vehicle["position"]) - np.array(position)
# Check if the volume of the bounding box is greater than 0.0005
if calculate_volume(bounds) > 0.0005:
if DEBUG_MODE:
print(
f"\t Vehicle {idx + 1} - Bounding Box: {bounds} - Position: {position} - Motion Vector: {motion_vector}"
)
# Add the vehicle information to the list of vehicles information
vehicles_info.append(
{
"id": idx,
"position": position,
"bounding_box": bounds,
"motion_vector": motion_vector,
}
)
return vehicles_info
def main():
"""
Retrieves point cloud frames from the dataset folder and processes them
to detect vehicles. Vehicles are tracked across frames and bounding boxes
are created for each vehicle. Furthermore, the vehicles and their bounding
boxes are visualized in an animated fashion. The results are saved to a CSV file.
Also calculates the latency for each frame and the average latency.
"""
# Get the list of PCD files and sort them numerically
pcd_files = os.listdir(path_frames)
pcd_files.sort(key=lambda x: int(os.path.splitext(x)[0]))
# Create a point cloud for visualization and a visualizer
geometry = o3d.geometry.PointCloud()
vis = o3d.visualization.Visualizer()
vis.create_window()
vis.add_geometry(geometry)
# Does not work for Open3d 0.17.0, Python 3.10.11
# Settings are not adjusted to fit the scene
# ctr = vis.get_view_control()
# ctr.set_zoom(0.01)
# ctr.set_lookat([0, 0, 0])
# ctr.set_front([0, 0, -1])
# ctr.set_up([0, 1, 0])
# List of latencies for each frame
latencies = []
# Previous frame
prev_frame = None
# Previous moving objects and tracked vehicles
prev_moving_objects = None
tracked_vehicles = None
# Iterate through all the PCD files
for i in range(len(pcd_files)):
start_time = time.time() # Start timer for latency
if DEBUG_MODE:
print(pcd_files[i])
# If it is the first frame, read the next frame instead of previous frame
if i == 0:
prev_frame = read_and_preprocess(
os.path.join(path_frames, pcd_files[i + 1])
)
# Read the current frame and preprocess it
curr_frame = read_and_preprocess(os.path.join(path_frames, pcd_files[i]))
# Detect moving objects in the current frame compared to the previous frame
moving_objects = detect_moving_objects(curr_frame, prev_frame)
# Get the vehicles from the moving objects
vehicles = get_vehicles(moving_objects)
vehicles_info = []
# Check if there are any vehicles detected in the current frame
if vehicles is None or len(vehicles) == 0:
# If no vehicles are detected, use the previous moving objects and tracked vehicles
moving_objects = prev_moving_objects
vehicles_info = tracked_vehicles
else:
# Get information about the vehicles detected in the current frame
vehicles_info = get_vehicle_infos(vehicles, tracked_vehicles)
geometries = []
# Update the tracked vehicles
tracked_vehicles = track_vehicles(vehicles_info, tracked_vehicles)
# Calculate the latency after getting all the information and before visualization
# end_time = time.time()
# Create a cluster for each vehicle and a bounding box for each vehicle
for vehicle in tracked_vehicles:
# Get the points within the bounding box
points = np.asarray(curr_frame.points)
cluster_indices = np.where(
(points[:, 0] >= vehicle["bounding_box"][0])
& (points[:, 0] <= vehicle["bounding_box"][3])
& (points[:, 1] >= vehicle["bounding_box"][1])
& (points[:, 1] <= vehicle["bounding_box"][4])
& (points[:, 2] >= vehicle["bounding_box"][2])
& (points[:, 2] <= vehicle["bounding_box"][5])
)[0]
# Create a point cloud for the points within the bounding box
veh_cluster = o3d.geometry.PointCloud()
veh_cluster.points = o3d.utility.Vector3dVector(points[cluster_indices])
# Color each vehicle's points differently
veh_cluster.paint_uniform_color(vehicle["color"])
# Add the cluster of vehicle and bounding box to the list of geometries
geometries.append(veh_cluster)
geometries.append(create_bounding_box(vehicle["bounding_box"]))
# Visualize moving objects and bounding boxes
vis.clear_geometries()
for geo in geometries:
vis.add_geometry(geo)
# Does not work for Open3d 0.17.0, Python 3.10.11
# Settings are not adjusted to fit the scene
# ctr.set_zoom(0.01)
# ctr.set_lookat([0, 0, 0])
# ctr.set_front([0, 0, -1])
# ctr.set_up([0, 1, 0])
vis.poll_events()
vis.update_renderer()
# Update the previous frame and moving objects
prev_frame = curr_frame
prev_moving_objects = moving_objects
# Save the results to a CSV file
save_results(tracked_vehicles, i)
# Calculate the latency for the current frame
end_time = time.time() # End timer for latency including visualization
latency = round(end_time - start_time, 5)
print(f"Frame {i} - Latency: {latency} seconds")
# Add the latency to the list of latencies
latencies.append(latency)
# Print the average latency
print(f"\nAverage latency: {round(np.mean(latencies), 5)} seconds")
# Save the latencies to a text file
if SAVE_LATENCIES:
formatted_latencies = [
"Frame " + str(idx) + " - Latency: " + str(latency) + " seconds"
for idx, latency in enumerate(latencies)
]
formatted_latencies.append(
f"\nAverage latency: {round(np.mean(latencies), 5)} seconds"
)
np.savetxt(
"latencies.txt",
formatted_latencies,
delimiter=",",
fmt="%s",
)
# Run the main function
if __name__ == "__main__":
main()