-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathraycast_sensor_testing.py
578 lines (450 loc) · 21.6 KB
/
raycast_sensor_testing.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
#!/usr/bin/env python
# Copyright (c) 2020 Computer Vision Center (CVC) at the Universitat Autonoma de
# Barcelona (UAB).
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
"""
Raycast sensor profiler
This script can be used to test, visualize and profile the raycast sensors,
LiDARs and Radar (radar visualization not available, sorry).
By default, the script render one RGB Camera and three LiDARS whose output
can be visualized in a window just running:
python raycast_sensor_testing.py
For profiling, you can choose the number of LiDARs and Radars and then use
the profiling option to run a series of simulations for points from 100k
to 1.5M per second. In this mode we do not render anything but processing
of the data is done.
For example for profiling one lidar:
python raycast_sensor_testing.py -ln 1 --profiling
For example for profiling one semantic lidar:
python raycast_sensor_testing.py -sln 1 --profiling
And for profiling one radar:
python raycast_sensor_testing.py -rn 1 --profiling
"""
import glob
import os
import sys
try:
sys.path.append(glob.glob('../carla/dist/carla-*%d.%d-%s.egg' % (
sys.version_info.major,
sys.version_info.minor,
'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])
except IndexError:
pass
import carla
import argparse
import random
import time
import numpy as np
try:
import pygame
from pygame.locals import K_ESCAPE
from pygame.locals import K_q
except ImportError:
raise RuntimeError('cannot import pygame, make sure pygame package is installed')
class CustomTimer:
def __init__(self):
try:
self.timer = time.perf_counter
except AttributeError:
self.timer = time.time
def time(self):
return self.timer()
class DisplayManager:
def __init__(self, grid_size, window_size, show_window=True):
if show_window:
pygame.init()
pygame.font.init()
self.display = pygame.display.set_mode(window_size, pygame.HWSURFACE | pygame.DOUBLEBUF)
else:
self.display = None
self.grid_size = grid_size
self.window_size = window_size
self.sensor_list = []
def get_window_size(self):
return [int(self.window_size[0]), int(self.window_size[1])]
def get_display_size(self):
return [int(self.window_size[0]/self.grid_size[0]), int(self.window_size[1]/self.grid_size[1])]
def get_display_offset(self, gridPos):
dis_size = self.get_display_size()
return [int(gridPos[0] * dis_size[0]), int(gridPos[1] * dis_size[1])]
def add_sensor(self, sensor):
self.sensor_list.append(sensor)
def get_sensor_list(self):
return self.sensor_list
def render(self):
if not self.render_enabled():
return
for s in self.sensor_list:
s.render()
pygame.display.flip()
def destroy(self):
for s in self.sensor_list:
s.destroy()
def render_enabled(self):
return self.display != None
class SensorManager:
def __init__(self, world, display_man, sensor_type, transform, attached, sensor_options, display_pos):
self.surface = None
self.world = world
self.display_man = display_man
self.display_pos = display_pos
self.sensor = self.init_sensor(sensor_type, transform, attached, sensor_options)
self.sensor_options = sensor_options
self.timer = CustomTimer()
self.time_processing = 0.0
self.tics_processing = 0
self.display_man.add_sensor(self)
def init_sensor(self, sensor_type, transform, attached, sensor_options):
if sensor_type == 'RGBCamera':
camera_bp = self.world.get_blueprint_library().find('sensor.camera.rgb')
disp_size = self.display_man.get_display_size()
camera_bp.set_attribute('image_size_x', str(disp_size[0]))
camera_bp.set_attribute('image_size_y', str(disp_size[1]))
for key in sensor_options:
camera_bp.set_attribute(key, sensor_options[key])
camera = self.world.spawn_actor(camera_bp, transform, attach_to=attached)
camera.listen(self.save_rgb_image)
return camera
elif sensor_type == 'LiDAR':
lidar_bp = self.world.get_blueprint_library().find('sensor.lidar.ray_cast')
lidar_bp.set_attribute('range', '100')
lidar_bp.set_attribute('dropoff_general_rate', lidar_bp.get_attribute('dropoff_general_rate').recommended_values[0])
lidar_bp.set_attribute('dropoff_intensity_limit', lidar_bp.get_attribute('dropoff_intensity_limit').recommended_values[0])
lidar_bp.set_attribute('dropoff_zero_intensity', lidar_bp.get_attribute('dropoff_zero_intensity').recommended_values[0])
for key in sensor_options:
lidar_bp.set_attribute(key, sensor_options[key])
lidar = self.world.spawn_actor(lidar_bp, transform, attach_to=attached)
lidar.listen(self.save_lidar_image)
return lidar
elif sensor_type == 'SemanticLiDAR':
lidar_bp = self.world.get_blueprint_library().find('sensor.lidar.ray_cast_semantic')
lidar_bp.set_attribute('range', '100')
for key in sensor_options:
lidar_bp.set_attribute(key, sensor_options[key])
lidar = self.world.spawn_actor(lidar_bp, transform, attach_to=attached)
lidar.listen(self.save_semanticlidar_image)
return lidar
elif sensor_type == "Radar":
radar_bp = self.world.get_blueprint_library().find('sensor.other.radar')
for key in sensor_options:
radar_bp.set_attribute(key, sensor_options[key])
radar = self.world.spawn_actor(radar_bp, transform, attach_to=attached)
radar.listen(self.save_radar_image)
return radar
else:
return None
def get_sensor(self):
return self.sensor
def save_rgb_image(self, image):
t_start = self.timer.time()
image.convert(carla.ColorConverter.Raw)
array = np.frombuffer(image.raw_data, dtype=np.dtype("uint8"))
array = np.reshape(array, (image.height, image.width, 4))
array = array[:, :, :3]
array = array[:, :, ::-1]
if self.display_man.render_enabled():
self.surface = pygame.surfarray.make_surface(array.swapaxes(0, 1))
t_end = self.timer.time()
self.time_processing += (t_end-t_start)
self.tics_processing += 1
def save_lidar_image(self, image):
t_start = self.timer.time()
disp_size = self.display_man.get_display_size()
lidar_range = 2.0*float(self.sensor_options['range'])
points = np.frombuffer(image.raw_data, dtype=np.dtype('f4'))
points = np.reshape(points, (int(points.shape[0] / 4), 4))
lidar_data = np.array(points[:, :2])
lidar_data *= min(disp_size) / lidar_range
lidar_data += (0.5 * disp_size[0], 0.5 * disp_size[1])
lidar_data = np.fabs(lidar_data) # pylint: disable=E1111
lidar_data = lidar_data.astype(np.int32)
lidar_data = np.reshape(lidar_data, (-1, 2))
lidar_img_size = (disp_size[0], disp_size[1], 3)
lidar_img = np.zeros((lidar_img_size), dtype=np.uint8)
lidar_img[tuple(lidar_data.T)] = (255, 255, 255)
if self.display_man.render_enabled():
self.surface = pygame.surfarray.make_surface(lidar_img)
t_end = self.timer.time()
self.time_processing += (t_end-t_start)
self.tics_processing += 1
def save_semanticlidar_image(self, image):
t_start = self.timer.time()
disp_size = self.display_man.get_display_size()
lidar_range = 2.0*float(self.sensor_options['range'])
points = np.frombuffer(image.raw_data, dtype=np.dtype('f4'))
points = np.reshape(points, (int(points.shape[0] / 6), 6))
lidar_data = np.array(points[:, :2])
lidar_data *= min(disp_size) / lidar_range
lidar_data += (0.5 * disp_size[0], 0.5 * disp_size[1])
lidar_data = np.fabs(lidar_data) # pylint: disable=E1111
lidar_data = lidar_data.astype(np.int32)
lidar_data = np.reshape(lidar_data, (-1, 2))
lidar_img_size = (disp_size[0], disp_size[1], 3)
lidar_img = np.zeros((lidar_img_size), dtype=np.uint8)
lidar_img[tuple(lidar_data.T)] = (255, 255, 255)
if self.display_man.render_enabled():
self.surface = pygame.surfarray.make_surface(lidar_img)
t_end = self.timer.time()
self.time_processing += (t_end-t_start)
self.tics_processing += 1
def save_radar_image(self, radar_data):
t_start = self.timer.time()
#print("Hola, saving Radar data!!")
# To get a numpy [[vel, altitude, azimuth, depth],...[,,,]]:
points = np.frombuffer(radar_data.raw_data, dtype=np.dtype('f4'))
points = np.reshape(points, (len(radar_data), 4))
t_end = self.timer.time()
self.time_processing += (t_end-t_start)
self.tics_processing += 1
def render(self):
if self.surface is not None:
offset = self.display_man.get_display_offset(self.display_pos)
self.display_man.display.blit(self.surface, offset)
def destroy(self):
self.sensor.destroy()
def one_run(args, client):
"""This function performed one test run using the args parameters
and connecting to the carla client passed.
"""
display_manager = None
vehicle = None
vehicle_list = []
prof_str = ""
timer = CustomTimer()
try:
# Getting the world and
world = client.get_world()
if args.sync:
traffic_manager = client.get_trafficmanager(8000)
settings = world.get_settings()
traffic_manager.set_synchronous_mode(True)
settings.synchronous_mode = True
settings.fixed_delta_seconds = 0.05
world.apply_settings(settings)
if args.profiling:
settings.no_rendering_mode = True
world.apply_settings(settings)
# Instanciating the vehicle to which we attached the sensors
bp = world.get_blueprint_library().filter('vehicle')[0]
if bp.has_attribute('color'):
color = random.choice(bp.get_attribute('color').recommended_values)
bp.set_attribute('color', color)
vehicle = world.spawn_actor(bp, world.get_map().get_spawn_points()[0])
vehicle_list.append(vehicle)
vehicle.set_autopilot(True)
# Display Manager organize all the sensors an its display in a window
display_manager = DisplayManager(grid_size=[2, 2], window_size=[args.width, args.height], show_window=args.render_window)
# If require, we instanciate the RGB camera
if args.render_cam:
SensorManager(world, display_manager, 'RGBCamera', carla.Transform(carla.Location(x=1.5, z=2.4)), vehicle, {}, [0, 0])
# If any, we instanciate the required lidars
lidar_points_per_second = args.lidar_points
if args.lidar_number >= 3:
SensorManager(world, display_manager, 'LiDAR', carla.Transform(carla.Location(x=0, z=2.4)), vehicle, {'channels' : '64', 'range' : '50', 'points_per_second': lidar_points_per_second, 'rotation_frequency': '20'}, [1, 0])
if args.lidar_number >= 2:
SensorManager(world, display_manager, 'LiDAR', carla.Transform(carla.Location(x=0, z=2.4)), vehicle, {'channels' : '64', 'range' : '100', 'points_per_second': lidar_points_per_second, 'rotation_frequency': '20'}, [0, 1])
if args.lidar_number >= 1:
SensorManager(world, display_manager, 'LiDAR', carla.Transform(carla.Location(x=0, z=2.4)), vehicle, {'channels' : '64', 'range' : '200', 'points_per_second': lidar_points_per_second, 'rotation_frequency': '20'}, [1, 1])
# If any, we instanciate the required semantic lidars
semanticlidar_points_per_second = args.semanticlidar_points
if args.semanticlidar_number >= 3:
SensorManager(world, display_manager, 'SemanticLiDAR', carla.Transform(carla.Location(x=0, z=2.4)), vehicle, {'channels' : '64', 'range' : '50', 'points_per_second': semanticlidar_points_per_second, 'rotation_frequency': '20'}, [1, 0])
if args.semanticlidar_number >= 2:
SensorManager(world, display_manager, 'SemanticLiDAR', carla.Transform(carla.Location(x=0, z=2.4)), vehicle, {'channels' : '64', 'range' : '100', 'points_per_second': semanticlidar_points_per_second, 'rotation_frequency': '20'}, [0, 1])
if args.semanticlidar_number >= 1:
SensorManager(world, display_manager, 'SemanticLiDAR', carla.Transform(carla.Location(x=0, z=2.4)), vehicle, {'channels' : '64', 'range' : '200', 'points_per_second': semanticlidar_points_per_second, 'rotation_frequency': '20'}, [1, 1])
# If any, we instanciate the required radars
radar_points_per_second = args.radar_points
if args.radar_number >= 3:
SensorManager(world, display_manager, 'Radar', carla.Transform(carla.Location(x=0, z=2.4), carla.Rotation(pitch=5, yaw=90)), vehicle, {'points_per_second': radar_points_per_second}, [2, 2])
if args.radar_number >= 2:
SensorManager(world, display_manager, 'Radar', carla.Transform(carla.Location(x=0, z=2.4), carla.Rotation(pitch=5, yaw=-90)), vehicle, {'points_per_second': radar_points_per_second}, [2, 2])
if args.radar_number >= 1:
SensorManager(world, display_manager, 'Radar', carla.Transform(carla.Location(x=0, z=2.4), carla.Rotation(pitch=5)), vehicle, {'points_per_second': radar_points_per_second}, [2, 2])
call_exit = False
time_init_sim = timer.time()
frame = 0
time0 = timer.time()
while True:
frame += 1
# Carla Tick
if args.sync:
world.tick()
else:
world.wait_for_tick()
# Render received data
display_manager.render()
# Time measurement for profiling or to output
if not args.profiling:
if frame == 30:
time_frames = timer.time() - time0
time_procc = 0
for sensor in display_manager.sensor_list:
time_procc += sensor.time_processing
print("FPS: %.3f %.3f %.3f" % (time_frames, 1.0/time_frames * 30, time_procc/time_frames))
frame = 0
for sensor in display_manager.sensor_list:
sensor.time_processing = 0
sensor.tics_processing = 0
time0 = timer.time()
if args.render_window:
for event in pygame.event.get():
if event.type == pygame.QUIT:
call_exit = True
elif event.type == pygame.KEYDOWN:
if event.key == K_ESCAPE or event.key == K_q:
call_exit = True
break
else:
if (timer.time() - time_init_sim) < 5.0:
frame = 0
for sensor in display_manager.sensor_list:
sensor.time_processing = 0
sensor.tics_processing = 0
time0 = timer.time()
if (timer.time() - time0) > 10.0:
time_frames = timer.time() - time0
time_procc = 0
for sensor in display_manager.sensor_list:
time_procc += sensor.time_processing
prof_str = "%-10s %-9s %-9s %-15s %-7.2f %-20.3f" % (args.lidar_number, args.semanticlidar_number, args.radar_number, lidar_points_per_second, float(frame) / time_frames, time_procc/time_frames)
break
if call_exit:
break
finally:
if display_manager:
display_manager.destroy()
client.apply_batch([carla.command.DestroyActor(x) for x in vehicle_list])
if args.sync:
settings = world.get_settings()
settings.synchronous_mode = False
settings.fixed_delta_seconds = None
world.apply_settings(settings)
if args.profiling:
settings.no_rendering_mode = False
world.apply_settings(settings)
return prof_str
def main():
argparser = argparse.ArgumentParser(
description='CARLA Sensor tutorial')
argparser.add_argument(
'--host',
metavar='H',
default='127.0.0.1',
help='IP of the host server (default: 127.0.0.1)')
argparser.add_argument(
'-p', '--port',
metavar='P',
default=2000,
type=int,
help='TCP port to listen to (default: 2000)')
argparser.add_argument(
'--sync',
action='store_true',
help='Synchronous mode execution')
argparser.add_argument(
'--async',
dest='sync',
action='store_false',
help='Asynchronous mode execution')
argparser.set_defaults(sync=True)
argparser.add_argument(
'--res',
metavar='WIDTHxHEIGHT',
default='1280x720',
help='window resolution (default: 1280x720)')
argparser.add_argument(
'-lp', '--lidar_points',
metavar='LP',
default='100000',
help='lidar points per second (default: "100000")')
argparser.add_argument(
'-ln', '--lidar_number',
metavar='LN',
default=3,
type=int,
choices=range(0, 4),
help='Number of lidars to render (from zero to three)')
argparser.add_argument(
'-slp', '--semanticlidar_points',
metavar='SLP',
default='100000',
help='semantic lidar points per second (default: "100000")')
argparser.add_argument(
'-sln', '--semanticlidar_number',
metavar='SLN',
default=0,
type=int,
choices=range(0, 4),
help='Number of semantic lidars to render (from zero to three)')
argparser.add_argument(
'-rp', '--radar_points',
metavar='RP',
default='100000',
help='radar points per second (default: "100000")')
argparser.add_argument(
'-rn', '--radar_number',
metavar='LN',
default=0,
type=int,
choices=range(0, 4),
help='Number of radars to render (from zero to three)')
argparser.add_argument(
'--camera',
dest='render_cam', action='store_true',
help='render also RGB camera (camera enable by default)')
argparser.add_argument('--no-camera',
dest='render_cam', action='store_false',
help='no render RGB camera (camera disable by default)')
argparser.set_defaults(render_cam=True)
argparser.add_argument(
'--profiling',
action='store_true',
help='Use the script in profiling mode. It measures the performance of \
the lidar for different number of points.')
argparser.set_defaults(profiling=False)
argparser.add_argument(
'--no-render-window',
action='store_false',
dest='render_window',
help='Render visualization window.')
argparser.set_defaults(render_window=True)
args = argparser.parse_args()
args.width, args.height = [int(x) for x in args.res.split('x')]
try:
client = carla.Client(args.host, args.port)
client.set_timeout(5.0)
if args.profiling:
print("-------------------------------------------------------")
print("# Running profiling with %s lidars, %s semantic lidars and %s radars." % (args.lidar_number, args.semanticlidar_number, args.radar_number))
args.render_cam = False
args.render_window = False
runs_output = []
points_range = ['100000', '200000', '300000', '400000', '500000',
'600000', '700000', '800000', '900000', '1000000',
'1100000', '1200000', '1300000', '1400000', '1500000']
for points in points_range:
args.lidar_points = points
args.semanticlidar_points = points
args.radar_points = points
run_str = one_run(args, client)
runs_output.append(run_str)
print("-------------------------------------------------------")
print("# Profiling of parallel raycast sensors (LiDAR and Radar)")
try:
import multiprocessing
print("#Number of cores: %d" % multiprocessing.cpu_count())
except ImportError:
print("#Hardware information not available, please install the " \
"multiprocessing module")
print("#NumLidars NumSemLids NumRadars PointsPerSecond FPS PercentageProcessing")
for o in runs_output:
print(o)
else:
one_run(args, client)
except KeyboardInterrupt:
print('\nCancelled by user. Bye!')
if __name__ == '__main__':
main()