-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
479 lines (385 loc) · 14.4 KB
/
Copy pathmain.py
File metadata and controls
479 lines (385 loc) · 14.4 KB
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
#!/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>.
"""
Script that render multiple sensors in the same pygame window
By default, it renders four cameras, one LiDAR and one Semantic LiDAR.
It can easily be configure for any different number of sensors.
To do that, check lines 290-308.
"""
from foxglove.messages import RawImage
import foxglove
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):
pygame.init()
pygame.font.init()
self.display = pygame.display.set_mode(
window_size, pygame.HWSURFACE | pygame.DOUBLEBUF
)
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[1]),
int(self.window_size[1] / self.grid_size[0]),
]
def get_display_offset(self, gridPos):
dis_size = self.get_display_size()
return [int(gridPos[1] * dis_size[0]), int(gridPos[0] * 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,
name
):
self.surface = None
self.name = name
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()
raw_image = image
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))
video_msg = RawImage(
data=raw_image.raw_data.tobytes(),
height=raw_image.height,
width=raw_image.width,
encoding="bgr8",
step=raw_image.frame_number,
)
foxglove.log(self.name, video_msg)
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()
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 run_simulation(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 = []
timer = CustomTimer()
try:
# Getting the world and
world = client.get_world()
original_settings = world.get_settings()
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)
# Instanciating the vehicle to which we attached the sensors
bp = world.get_blueprint_library().filter("charger_2020")[0]
vehicle = world.spawn_actor(
bp, random.choice(world.get_map().get_spawn_points())
)
vehicle_list.append(vehicle)
vehicle.set_autopilot(True)
# Display Manager organize all the sensors an its display in a window
# If can easily configure the grid and the total window size
display_manager = DisplayManager(
grid_size=[2, 3], window_size=[args.width, args.height]
)
# Then, SensorManager can be used to spawn RGBCamera, LiDARs and SemanticLiDARs as needed
# and assign each of them to a grid position,
SensorManager(
world,
display_manager,
"RGBCamera",
carla.Transform(carla.Location(x=0, z=2.4), carla.Rotation(yaw=-90)),
vehicle,
{},
display_pos=[0, 0],
name="/camera-1"
)
SensorManager(
world,
display_manager,
"RGBCamera",
carla.Transform(carla.Location(x=0, z=2.4), carla.Rotation(yaw=+00)),
vehicle,
{},
display_pos=[0, 1],
name="/camera-2",
)
SensorManager(
world,
display_manager,
"RGBCamera",
carla.Transform(carla.Location(x=0, z=2.4), carla.Rotation(yaw=+90)),
vehicle,
{},
display_pos=[0, 2],
name="/camera-3",
)
SensorManager(
world,
display_manager,
"RGBCamera",
carla.Transform(carla.Location(x=0, z=2.4), carla.Rotation(yaw=180)),
vehicle,
{},
display_pos=[1, 1],
name="/camera-4"
)
SensorManager(
world,
display_manager,
"LiDAR",
carla.Transform(carla.Location(x=0, z=2.4)),
vehicle,
{
"channels": "64",
"range": "100",
"points_per_second": "250000",
"rotation_frequency": "20",
},
display_pos=[1, 0],
name="LiDAR",
)
SensorManager(
world,
display_manager,
"SemanticLiDAR",
carla.Transform(carla.Location(x=0, z=2.4)),
vehicle,
{
"channels": "64",
"range": "100",
"points_per_second": "100000",
"rotation_frequency": "20",
},
display_pos=[1, 2],
name="SemanticLiDAR"
)
# Simulation loop
call_exit = False
time_init_sim = timer.time()
while True:
# Carla Tick
if args.sync:
world.tick()
else:
world.wait_for_tick()
# Render received data
display_manager.render()
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
if call_exit:
break
finally:
if display_manager:
display_manager.destroy()
client.apply_batch([carla.command.DestroyActor(x) for x in vehicle_list])
world.apply_settings(original_settings)
foxglove.start_server()
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)",
)
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)
run_simulation(args, client)
except KeyboardInterrupt:
print("\nCancelled by user. Bye!")
if __name__ == "__main__":
main()