Skip to content

Commit 0828b04

Browse files
authored
创建模块carla_CAM,功能为carla的CAM可视化 (#5209)
* 统计贡献度 * add_contribution_actions * Delete Contribution_analysis.py * first commit to readme * first commit * Rename carla_CAM.py to main.py * Delete src/Vehicle_Object_Detection_Simulation directory * modify name and readme * modify name * 修改绝对路径为相对路径 * Delete src/carla_cam directory
1 parent 243dca1 commit 0828b04

15 files changed

Lines changed: 3023 additions & 0 deletions

src/carla_CAM/Dockerfile

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
FROM carlasim/carla:latest
2+
3+
SHELL ["/bin/bash", "-c"]
4+
5+
WORKDIR /carla-simulator-cam
6+
7+
COPY carla-simulator-cam carla-simulator-cam/
8+
RUN apt-get -y update
9+
RUN apt-get install -y python3-pip
10+
RUN apt-get install -y x11-apps
11+
RUN pip3 install -r requirements.txt
12+
13+
CMD ["bash"]

src/carla_CAM/LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2022 Pablo Roca
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

src/carla_CAM/README.md

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# carla-simulator-CAM
2+
用于在 Carla 模拟器中使用类激活映射(Class Activation Mapping, CAM)技术测试卷积神经网络(CNN)的应用。
3+
该项目旨在提高自动驾驶背景下深度学习模型的透明度。
4+
5+
## 使用方法
6+
运行主脚本前,保证hutb模拟器在运行
7+
8+
## 功能特性
9+
10+
应用通过 `carla_CAM.py` 脚本启动,并自动运行所有后台进程。
11+
- 如果模拟器尚未运行,应用会自动启动它。
12+
- 自动部署交通流(车辆和行人)。
13+
- 启动基于 Pygame 的交互式窗口,您可以在其中可视化所选的传感器并与它们交互。
14+
- 应用还会管理垃圾回收和进程终止。如果希望在退出应用后保持模拟器继续运行,可以使用 `--keepsim` 标志,以便下次更快启动应用。
15+
16+
### 运行中的交互选择
17+
18+
应用提供了在运行时交互式选择不同可视化参数的方式。Pygame 执行窗口会读取键盘和鼠标的输入事件(即输入外设的交互)。我们可以捕获事件类型并创建一个选项菜单。交互方式分为两类:
19+
20+
#### 键盘输入
21+
22+
- **空格键(SPACE)**:暂停模拟并显示所选 CAM 技术得到的 saliency mask。如果尚未选择任何技术,则不会暂停模拟,并提示用户选择一种技术。如果模拟已暂停,则恢复运行。
23+
- **M 键**:停止模拟并显示 CAM 技术选择菜单。如果在模拟暂停(显示 saliency mask)时按下,则会再次弹出方法菜单,允许用户选择不同的方法以比较生成的 saliency mask。
24+
- **N 键**:停止模拟并显示 CNN 架构选择菜单。
25+
- **T 键**:对模型进行一次前向传播,返回检测到的前 5 个类别。
26+
- **Q 键 / ESC 键**:停止应用和模拟器的运行(除非启动时使用了 `--keepsim` 标志)。
27+
28+
#### 鼠标输入
29+
30+
- **模拟运行时**:允许用户选择要可视化的输入传感器。点击传感器区域即可选择该传感器的画面作为模型评估的输入图像。
31+
- **菜单显示时**:允许用户点击并选择菜单中的某一项。
32+
33+
### 支持的 CNN 架构
34+
35+
- ResNet
36+
- AlexNet
37+
- VGGNet
38+
- YOLOv5
39+
40+
### 兼容的 CAM 技术
41+
42+
#### 基于梯度的方法
43+
- Grad-CAM
44+
- Grad-CAM++
45+
- XGrad-CAM
46+
- FullGrad
47+
48+
#### 非梯度方法
49+
- Score-CAM
50+
- Ablation-CAM
51+
- Eigen-CAM
52+
53+
## 环境配置
54+
`pip install -r requirements`
55+
### 系统要求
56+
- **操作系统**:仅在windows10下进行了测试
57+
- **Python 版本**:python 3.8
58+
- **HUTB 模拟器**:本应用基于HUTB(定制版 CARLA)运行。请选择:
59+
- HUTB 模拟器(版本需与提供的 `.whl` 文件匹配)
60+
61+
### 注意项
62+
由于是在hutb模拟器上进行测试,不要将原生的python API 与hutb 提供的专用python API 混乱,不然导致无法运行
63+
64+
65+
66+

src/carla_CAM/carlacomms/__init__.py

Whitespace-only changes.
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
2+
import glob
3+
import os
4+
import sys
5+
import random
6+
import time
7+
import numpy as np
8+
import cv2
9+
import pygame
10+
from pygame.locals import KMOD_CTRL
11+
from pygame.locals import K_ESCAPE
12+
from pygame.locals import K_q
13+
from pygame import key
14+
import numpy as np
15+
16+
# ==============================================================================
17+
# -- Find CARLA module ---------------------------------------------------------
18+
# ==============================================================================
19+
try:
20+
sys.path.append(glob.glob('../carla/dist/carla-*%d.%d-%s.egg' % (
21+
sys.version_info.major,
22+
sys.version_info.minor,
23+
'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])
24+
except IndexError:
25+
pass
26+
27+
# ==============================================================================
28+
# -- Add PythonAPI for release mode --------------------------------------------
29+
# ==============================================================================
30+
try:
31+
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/carla')
32+
except IndexError:
33+
pass
34+
35+
import carla
36+
37+
#*******************************************************************************
38+
IM_WIDTH = 640
39+
IM_HEIGHT = 480
40+
IM_FOV = 100
41+
IM_SHUTTER = 30
42+
TIMEOUT = 20
43+
CAM_LOC_X = 3
44+
CAM_LOC_Z = 1.3
45+
46+
47+
class sensor_platform():
48+
"""Class to create a car with RGB sensors and pass the image to the visualizer"""
49+
def __init__(self):
50+
self.width = IM_WIDTH
51+
self.height = IM_HEIGHT
52+
self.fov = IM_FOV
53+
self.shutter = IM_SHUTTER
54+
self.sensor = None
55+
self.actor_list = []
56+
self.sensor_list = []
57+
self.client = carla.Client("localhost", 2000)
58+
self.client.set_timeout(TIMEOUT)
59+
self.world = self.client.get_world()
60+
traffic_manager = self.client.get_trafficmanager(8000)
61+
traffic_manager.set_synchronous_mode(True)
62+
63+
# synchronous mode:
64+
settings = self.world.get_settings()
65+
print("Is client in synchrony mode? ",settings.synchronous_mode)
66+
settings.synchronous_mode = True
67+
settings.fixed_delta_seconds = 0.05
68+
self.world.apply_settings(settings)
69+
70+
self.blueprint_library = self.world.get_blueprint_library()
71+
bp = self.blueprint_library.filter("mustang")[0]
72+
spawn_point = random.choice(self.world.get_map().get_spawn_points())
73+
# To solve spawn collision for the sensor platform and avoid execution crash
74+
for spawn_collision in range(1, 10):
75+
try:
76+
self.vehicle = self.world.spawn_actor(bp, spawn_point)
77+
self.vehicle.set_autopilot(True) #initiate with autopilot
78+
self.actor_list.append(self.vehicle)
79+
except:
80+
print(f'Sensor platform spawn failed. collision counter: {spawn_collision} ')
81+
spawn_point = random.choice(self.world.get_map().get_spawn_points())
82+
time.sleep(0.5)
83+
pass
84+
85+
def __del__(self):
86+
for actor in self.actor_list:
87+
print(f'actor {actor}, destroyed')
88+
actor.destroy()
89+
for sensor in self.sensor_list:
90+
print(f'sensor {sensor}, destroyed')
91+
sensor.destroy()
92+
print("all actors and sensors destroyed")
93+
94+
def set_sensor(self, bp_name = "sensor.camera.rgb"):
95+
cam_bp = self.blueprint_library.find(bp_name)
96+
cam_bp.set_attribute("image_size_x", f"{self.width}")
97+
cam_bp.set_attribute("image_size_y", f"{self.height}")
98+
cam_bp.set_attribute("fov", f"{self.fov}")
99+
cam_bp.set_attribute("shutter_speed", f"{self.shutter}")
100+
spawn_point = carla.Transform(carla.Location(x=CAM_LOC_X, z=CAM_LOC_Z))
101+
self.sensor = self.world.spawn_actor(cam_bp, spawn_point, attach_to=self.vehicle)
102+
self.sensor_list.append(self.sensor)
103+
return self.sensor
104+
105+
106+
# to RGB avoiding alpha
107+
def carla_to_cv(self, image, visualize=False):
108+
i = np.array(image.raw_data) # one dimension array
109+
i2 = i.reshape((IM_HEIGHT, IM_WIDTH, 4))
110+
i3 = i2[:,:,:3] #only get rgb avoids alpha
111+
if visualize:
112+
cv2.imshow("RGB Sensor: Front Camera",i3)
113+
c = cv2.waitKey(1) # ASCII 'Esc' value
114+
if c == 27:
115+
print('Closing simulator camera, shutting down application...')
116+
cv2.destroyAllWindows()
117+
exit()
118+
return i3
119+
120+
def main():
121+
platform = sensor_platform()
122+
sensor = platform.set_sensor()
123+
sensor.listen(lambda data: platform.carla_to_cv(data))
124+
while 1:
125+
time.sleep(20)
126+
127+
if __name__ == "__main__":
128+
main()

0 commit comments

Comments
 (0)