From ef5739fa17944d197f9548ff7efa9d87be84b33e Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Sat, 13 Sep 2025 13:29:56 +0800 Subject: [PATCH 01/34] =?UTF-8?q?=E5=85=B7=E8=BA=AB=E4=BA=BA=E8=A7=86?= =?UTF-8?q?=E8=A7=89=E8=AF=86=E5=88=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/humanoid_hlaa/README.md.txt | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 src/humanoid_hlaa/README.md.txt diff --git a/src/humanoid_hlaa/README.md.txt b/src/humanoid_hlaa/README.md.txt new file mode 100644 index 0000000000..e69de29bb2 From 49ffa4468031ae0ed0347aae5cbe9989617a940d Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Sat, 13 Sep 2025 14:59:04 +0800 Subject: [PATCH 02/34] =?UTF-8?q?=E5=85=B7=E8=BA=AB=E4=BA=BA=E8=A7=86?= =?UTF-8?q?=E8=A7=89=E8=AF=86=E5=88=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../README.md.txt | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/{humanoid_hlaa => Humanoid_Machine Vision Recognition}/README.md.txt (100%) diff --git a/src/humanoid_hlaa/README.md.txt b/src/Humanoid_Machine Vision Recognition/README.md.txt similarity index 100% rename from src/humanoid_hlaa/README.md.txt rename to src/Humanoid_Machine Vision Recognition/README.md.txt From 9f98a37d03d832e2212e18cc06772ca4683e4c6a Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Sat, 13 Sep 2025 17:06:36 +0800 Subject: [PATCH 03/34] =?UTF-8?q?=E5=85=B7=E8=BA=AB=E4=BA=BA=E8=A7=86?= =?UTF-8?q?=E8=A7=89=E8=AF=86=E5=88=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../README.md.txt | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/{Humanoid_Machine Vision Recognition => Humanoid_Machine_vision_Recognition}/README.md.txt (100%) diff --git a/src/Humanoid_Machine Vision Recognition/README.md.txt b/src/Humanoid_Machine_vision_Recognition/README.md.txt similarity index 100% rename from src/Humanoid_Machine Vision Recognition/README.md.txt rename to src/Humanoid_Machine_vision_Recognition/README.md.txt From e41aeda5633ca9828875065dfffebbc551e0b9ac Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Sat, 13 Sep 2025 17:16:51 +0800 Subject: [PATCH 04/34] =?UTF-8?q?=E5=85=B7=E8=BA=AB=E4=BA=BA=E8=A7=86?= =?UTF-8?q?=E8=A7=89=E8=AF=86=E5=88=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../README.md.txt | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/{humanoid_hlaa => humanoid_machine_vision_recognition}/README.md.txt (100%) diff --git a/src/humanoid_hlaa/README.md.txt b/src/humanoid_machine_vision_recognition/README.md.txt similarity index 100% rename from src/humanoid_hlaa/README.md.txt rename to src/humanoid_machine_vision_recognition/README.md.txt From b30548bc836935aa7293ebc2a49a04fa3969a0fd Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Sat, 13 Sep 2025 18:14:34 +0800 Subject: [PATCH 05/34] =?UTF-8?q?=E5=85=B7=E8=BA=AB=E4=BA=BA=E8=A7=86?= =?UTF-8?q?=E8=A7=89=E8=AF=86=E5=88=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Humanoid_Machine_vision_Recognition/README.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 src/Humanoid_Machine_vision_Recognition/README.md diff --git a/src/Humanoid_Machine_vision_Recognition/README.md b/src/Humanoid_Machine_vision_Recognition/README.md new file mode 100644 index 0000000000..e69de29bb2 From 26a59994be27996485f7dd4e639edb258e28fd1a Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Sat, 13 Sep 2025 18:22:45 +0800 Subject: [PATCH 06/34] README.md.txt --- src/humanoid_machine_vision_recognition/README.md.txt | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 src/humanoid_machine_vision_recognition/README.md.txt diff --git a/src/humanoid_machine_vision_recognition/README.md.txt b/src/humanoid_machine_vision_recognition/README.md.txt deleted file mode 100644 index e69de29bb2..0000000000 From 327d7b050e92fe679b8fe3a97550e0f058db91a5 Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Sat, 13 Sep 2025 18:59:14 +0800 Subject: [PATCH 07/34] =?UTF-8?q?=E5=A4=84=E7=90=86=20README.md.txt=20?= =?UTF-8?q?=E7=9B=B8=E5=85=B3=E5=8F=98=E6=9B=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Humanoid_Machine_vision_Recognition/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Humanoid_Machine_vision_Recognition/README.md b/src/Humanoid_Machine_vision_Recognition/README.md index e69de29bb2..e89b7ad11a 100644 --- a/src/Humanoid_Machine_vision_Recognition/README.md +++ b/src/Humanoid_Machine_vision_Recognition/README.md @@ -0,0 +1 @@ +ÕâÊÇһ¸ö¾ßÉíÈËÊӾõʶ±ðϵͳ \ No newline at end of file From 90c0ed5a694832fbad2179af5a06428442abef8a Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Sat, 13 Sep 2025 19:24:01 +0800 Subject: [PATCH 08/34] =?UTF-8?q?=E5=A4=84=E7=90=86=20README.md=20?= =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=92=8CREADME.md.txt=E5=88=A0=E9=99=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Humanoid_Machine_vision_Recognition/README.md | 1 - src/Humanoid_Machine_vision_Recognition/README.md.txt | 0 2 files changed, 1 deletion(-) delete mode 100644 src/Humanoid_Machine_vision_Recognition/README.md.txt diff --git a/src/Humanoid_Machine_vision_Recognition/README.md b/src/Humanoid_Machine_vision_Recognition/README.md index e89b7ad11a..e69de29bb2 100644 --- a/src/Humanoid_Machine_vision_Recognition/README.md +++ b/src/Humanoid_Machine_vision_Recognition/README.md @@ -1 +0,0 @@ -ÕâÊÇһ¸ö¾ßÉíÈËÊӾõʶ±ðϵͳ \ No newline at end of file diff --git a/src/Humanoid_Machine_vision_Recognition/README.md.txt b/src/Humanoid_Machine_vision_Recognition/README.md.txt deleted file mode 100644 index e69de29bb2..0000000000 From 394d49f9559eed7c744ea471b05b1258dd5373ba Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Mon, 15 Sep 2025 08:52:59 +0800 Subject: [PATCH 09/34] Update README.md --- src/Humanoid_Machine_vision_Recognition/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Humanoid_Machine_vision_Recognition/README.md b/src/Humanoid_Machine_vision_Recognition/README.md index e69de29bb2..e1af47c7fa 100644 --- a/src/Humanoid_Machine_vision_Recognition/README.md +++ b/src/Humanoid_Machine_vision_Recognition/README.md @@ -0,0 +1 @@ +这是具身人视觉识别模块 From a4f0e09ac2347995aa98bd509cde48c1ee0f0204 Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Mon, 22 Sep 2025 10:04:09 +0800 Subject: [PATCH 10/34] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=A0=94=E7=A9=B6?= =?UTF-8?q?=E8=AF=BE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/detection/README.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 src/detection/README.md diff --git a/src/detection/README.md b/src/detection/README.md new file mode 100644 index 0000000000..0d16c3c448 --- /dev/null +++ b/src/detection/README.md @@ -0,0 +1 @@ +2D与3D检测 \ No newline at end of file From d8a4de519c0c0ce0111e8f4db35f67e72a04a768 Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Mon, 22 Sep 2025 10:23:36 +0800 Subject: [PATCH 11/34] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=A0=94=E7=A9=B6?= =?UTF-8?q?=E8=AF=BE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Humanoid_Machine_vision_Recognition/README.md | 1 - 1 file changed, 1 deletion(-) delete mode 100644 src/Humanoid_Machine_vision_Recognition/README.md diff --git a/src/Humanoid_Machine_vision_Recognition/README.md b/src/Humanoid_Machine_vision_Recognition/README.md deleted file mode 100644 index e1af47c7fa..0000000000 --- a/src/Humanoid_Machine_vision_Recognition/README.md +++ /dev/null @@ -1 +0,0 @@ -这是具身人视觉识别模块 From 7daf1ef2ac04e9c336fcb5281a0d0517b54047bb Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Tue, 18 Nov 2025 08:28:40 +0800 Subject: [PATCH 12/34] =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E7=9B=AE=E5=BD=95=E4=BB=A5=E5=8F=8A=E5=85=B6=E5=8C=85=E5=90=AB?= =?UTF-8?q?=E7=9A=84README=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/detection/README.md | 1 - 1 file changed, 1 deletion(-) delete mode 100644 src/detection/README.md diff --git a/src/detection/README.md b/src/detection/README.md deleted file mode 100644 index 0d16c3c448..0000000000 --- a/src/detection/README.md +++ /dev/null @@ -1 +0,0 @@ -2D与3D检测 \ No newline at end of file From deca5a8916aad67e1b818a796794205319a5fbb8 Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Tue, 18 Nov 2025 08:45:12 +0800 Subject: [PATCH 13/34] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=96=B0=E7=9A=84?= =?UTF-8?q?=E8=87=AA=E8=BF=B0=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/InterconVis_PedSafety_Enh/README.md | 113 ++++++++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 src/InterconVis_PedSafety_Enh/README.md diff --git a/src/InterconVis_PedSafety_Enh/README.md b/src/InterconVis_PedSafety_Enh/README.md new file mode 100644 index 0000000000..afbc3105da --- /dev/null +++ b/src/InterconVis_PedSafety_Enh/README.md @@ -0,0 +1,113 @@ +# CVIPS: Connected Vision for Increased Pedestrian Safety +Implementation of the CVIPS project. +- [X] Dataset +- [X] CARLA data generation code + + + +## Dataset +The CVIPS dataset is available [here](https://drive.google.com/drive/folders/1gCCrIslzVkupyF0lj_1I9qXTB2_a4tjd?usp=drive_link). + + + + + +## Installation +Please check [installation](https://carla.readthedocs.io/en/0.9.14/build_windows) on how to setup CARLA for windows + + + +## Dataset Generation +Our dataset is generated using the CARLA simulator, providing diverse scenarios for collaborative perception. + +### Running the Data Generation Script + +1. Clone the repository: + ``` + git clone https://github.com/cvips/CVIPS.git + cd CVIPS + ``` + +2. Install the required dependencies: + ``` + pip install -r requirements.txt + ``` + +3. Ensure CARLA is properly installed and running. Start the CARLA server in a separate terminal: + ``` + /path/to/carla/CarlaUE4.exe + ``` + +4. Run the data generation script: + ``` + python cvips_generation.py + ``` + + This script will connect to the CARLA server and generate the dataset based on the specified parameters. + +Note: Make sure to adjust the CARLA server path and any configuration parameters in `cvips_generation.py` as needed for your specific setup. + +### Sample Examples + +Here are some example commands to generate different scenarios: + +1. Four-way intersection in Town10HD with clear weather at noon: + ``` + python cvips_generation.py --town Town10HD --intersection 4way --setup wsee --weather clear --time_of_the_day noon --crowd_level medium --crossing_percentage 0.1 --seed_value 23 --scenario scenario00001 + ``` + +2. Four-way intersection in Town04 with rainy weather at sunset: + ``` + python cvips_generation.py --town Town04 --intersection 4way --setup wwss --weather rainy --time_of_the_day sunset --crowd_level medium --crossing_percentage 0.1 --seed_value 42 --scenario scenario00002 + ``` + +3. Three-way intersection in Town05 with clear weather at night: + ``` + python cvips_generation.py --town Town05 --intersection 3way --setup wwss --weather clear --time_of_the_day night --crowd_level medium --crossing_percentage 0.1 --seed_value 73 --scenario scenario00005 + ``` + +4. Four-way intersection in Town10HD with cloudy weather at noon: + ``` + python cvips_generation.py --town Town10HD --intersection 4way --setup wwws --weather cloudy --time_of_the_day noon --crowd_level medium --crossing_percentage 0.1 --seed_value 101 --scenario scenario00011 + ``` + +These examples demonstrate various combinations of towns, intersection types, weather conditions, times of day, and camera setups. Users can modify these parameters to generate different scenarios as needed. + +### Sample Visualizations + +We provide visualizations to demonstrate different perspectives in our dataset: +(this can be done using [Code/data_viz.py](Code\data_viz.py)) +1. **Infrastructure View** (6 cameras) + Infrastructure View + This visualization shows the scene from fixed infrastructure cameras, providing a comprehensive view of the intersection from multiple angles. + +2. **Vehicle View** (6 cameras) + Vehicle View + This visualization demonstrates the perspective from a moving vehicle, showcasing the view from various angles around the vehicle. + +3. **Collaborative View** (4 cameras) + Collaborative View + This visualization combines views from both vehicles and infrastructure, illustrating the collaborative perception aspect of our dataset. + + +- Multiple camera perspectives (infrastructure, vehicle-mounted, and collaborative) +- Various weather conditions and times of day () +- Diverse traffic scenarios with multiple vehicles and pedestrians setup (controlled by seeds, number of pedestrians, number of vehicles to be spawned) + + + +## For Detection in collaborative setup check the documentation of V2XFormer +First, prepare the dataset with this format [data_preparation](docs/data_preparation.md) . +Then, use [V2XFormer](https://github.com/tianqi-wang1996/DeepAccident) according to the instructions here +1. [Installation](https://github.com/tianqi-wang1996/DeepAccident/blob/main/docs/installation.md) +2. [Training and Evaluation](https://github.com/tianqi-wang1996/DeepAccident/blob/main/docs/getting_started.md) -- adjust the datapaths and number of classes accordingly + +## Acknowledgement +This project is based on the following open-source projects: [BEVerse](https://github.com/zhangyp15/BEVerse), [Fiery](https://github.com/wayveai/fiery), [open-mmlab](https://github.com/open-mmlab), and [DeepAccident](https://arxiv.org/pdf/2304.01168). + +## Citation + + + + +``` From d0405ffa81a15de061a31ba015ae57b658462427 Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Tue, 18 Nov 2025 09:11:21 +0800 Subject: [PATCH 14/34] =?UTF-8?q?=E6=89=8B=E5=8A=A8=E5=88=9B=E5=BB=BA?= =?UTF-8?q?=E6=96=87=E4=BB=B6=EF=BC=8C=E5=AE=9E=E7=8E=B0CARLA=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E4=B8=8E=E6=95=B0=E6=8D=AE=E7=94=9F=E6=88=90=E7=9A=84?= =?UTF-8?q?=E6=A0=B8=E5=BF=83=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cvips_generation.py | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 src/InterconVis_PedSafety_Enh/cvips_generation.py diff --git a/src/InterconVis_PedSafety_Enh/cvips_generation.py b/src/InterconVis_PedSafety_Enh/cvips_generation.py new file mode 100644 index 0000000000..267be481a7 --- /dev/null +++ b/src/InterconVis_PedSafety_Enh/cvips_generation.py @@ -0,0 +1,24 @@ +import carla +import time + +# 连接CARLA服务(默认端口2000) +client = carla.Client('localhost', 2000) +client.set_timeout(10.0) +world = client.get_world() + +# 示例:生成车辆并采集数据 +blueprint_library = world.get_blueprint_library() +vehicle_bp = blueprint_library.filter('model3')[0] +spawn_point = world.get_map().get_spawn_points()[0] +vehicle = world.spawn_actor(vehicle_bp, spawn_point) + +try: + # 模拟数据采集(可根据需求扩展) + print("开始采集数据...") + for _ in range(5): + transform = vehicle.get_transform() + print(f"车辆位置: {transform.location}") + time.sleep(1) +finally: + vehicle.destroy() + print("数据采集结束") \ No newline at end of file From 740fe77c998fa707264ccf338778b90617733fc4 Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Tue, 18 Nov 2025 09:25:28 +0800 Subject: [PATCH 15/34] =?UTF-8?q?=E4=BC=98=E5=8C=96=E6=94=B9=E8=BF=9Bcarla?= =?UTF-8?q?=E8=BF=9E=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cvips_generation.py | 43 ++++++++++--------- 1 file changed, 23 insertions(+), 20 deletions(-) diff --git a/src/InterconVis_PedSafety_Enh/cvips_generation.py b/src/InterconVis_PedSafety_Enh/cvips_generation.py index 267be481a7..fce42067ca 100644 --- a/src/InterconVis_PedSafety_Enh/cvips_generation.py +++ b/src/InterconVis_PedSafety_Enh/cvips_generation.py @@ -1,24 +1,27 @@ import carla +import argparse import time -# 连接CARLA服务(默认端口2000) -client = carla.Client('localhost', 2000) -client.set_timeout(10.0) -world = client.get_world() +# 参数解析+CARLA连接+地图加载 +if __name__ == "__main__": + # 1. 解析命令行参数(带输入校验) + parser = argparse.ArgumentParser(description='CVIPS场景数据生成工具') + parser.add_argument('--town', type=str, required=True, choices=['Town04', 'Town10HD', 'Town07'], + help='CARLA城镇地图(支持:Town04/Town10HD/Town07)') + parser.add_argument('--intersection', type=str, required=True, choices=['3way', '4way'], + help='路口类型(3way=三叉路口,4way=四岔路口)') + parser.add_argument('--weather', type=str, required=True, choices=['clear', 'rainy', 'cloudy'], + help='天气条件(clear=晴天,rainy=雨天,cloudy=阴天)') + parser.add_argument('--time_of_day', type=str, required=True, choices=['noon', 'sunset', 'night'], + help='时段(noon=中午,sunset=日落,night=夜晚)') + args = parser.parse_args() -# 示例:生成车辆并采集数据 -blueprint_library = world.get_blueprint_library() -vehicle_bp = blueprint_library.filter('model3')[0] -spawn_point = world.get_map().get_spawn_points()[0] -vehicle = world.spawn_actor(vehicle_bp, spawn_point) - -try: - # 模拟数据采集(可根据需求扩展) - print("开始采集数据...") - for _ in range(5): - transform = vehicle.get_transform() - print(f"车辆位置: {transform.location}") - time.sleep(1) -finally: - vehicle.destroy() - print("数据采集结束") \ No newline at end of file + try: + # 2. 连接CARLA服务器(设置超时重试机制) + client = carla.Client('localhost', 2000) + client.set_timeout(15.0) + client.load_world(args.town) # 加载指定城镇 + world = client.get_world() + print(f"✅ 成功连接CARLA并加载地图:{args.town}") + except Exception as e: + print(f"❌ 连接失败:{str(e)},请检查CARLA服务器是否启动") \ No newline at end of file From dc692080fe01be4fc55580ae00bcb9a2bfee935b Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Tue, 18 Nov 2025 17:13:41 +0800 Subject: [PATCH 16/34] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=86=B2=E7=AA=81?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cvips_generation.py | 30 ++----------------- 1 file changed, 2 insertions(+), 28 deletions(-) diff --git a/src/InterconVis_PedSafety_Enh/cvips_generation.py b/src/InterconVis_PedSafety_Enh/cvips_generation.py index 667c36a007..20f8b1975d 100644 --- a/src/InterconVis_PedSafety_Enh/cvips_generation.py +++ b/src/InterconVis_PedSafety_Enh/cvips_generation.py @@ -1,9 +1,8 @@ import carla -<<<<<<< HEAD import argparse import time -# 参数解析+CARLA连接+地图加载 +# 完整代码:参数解析+CARLA连接+地图加载 if __name__ == "__main__": # 1. 解析命令行参数(带输入校验) parser = argparse.ArgumentParser(description='CVIPS场景数据生成工具') @@ -25,29 +24,4 @@ world = client.get_world() print(f"✅ 成功连接CARLA并加载地图:{args.town}") except Exception as e: - print(f"❌ 连接失败:{str(e)},请检查CARLA服务器是否启动") -======= -import time - -# 连接CARLA服务(默认端口2000) -client = carla.Client('localhost', 2000) -client.set_timeout(10.0) -world = client.get_world() - -# 示例:生成车辆并采集数据 -blueprint_library = world.get_blueprint_library() -vehicle_bp = blueprint_library.filter('model3')[0] -spawn_point = world.get_map().get_spawn_points()[0] -vehicle = world.spawn_actor(vehicle_bp, spawn_point) - -try: - # 模拟数据采集(可根据需求扩展) - print("开始采集数据...") - for _ in range(5): - transform = vehicle.get_transform() - print(f"车辆位置: {transform.location}") - time.sleep(1) -finally: - vehicle.destroy() - print("数据采集结束") ->>>>>>> 2aed4c9d022da20198dd176e94c525d3c39b4c39 + print(f"❌ 连接失败:{str(e)},请检查CARLA服务器是否启动") \ No newline at end of file From d3b396368371f6cdda6ebfb83c7c90d214c56655 Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Thu, 20 Nov 2025 10:36:56 +0800 Subject: [PATCH 17/34] =?UTF-8?q?=E4=BC=98=E5=8C=96=E8=BF=9E=E6=8E=A5?= =?UTF-8?q?=E5=92=8C=E8=B5=84=E6=BA=90=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cvips_generation.py | 128 ++++++++++++++++-- 1 file changed, 118 insertions(+), 10 deletions(-) diff --git a/src/InterconVis_PedSafety_Enh/cvips_generation.py b/src/InterconVis_PedSafety_Enh/cvips_generation.py index 20f8b1975d..223b86f448 100644 --- a/src/InterconVis_PedSafety_Enh/cvips_generation.py +++ b/src/InterconVis_PedSafety_Enh/cvips_generation.py @@ -1,9 +1,12 @@ import carla import argparse import time +import atexit -# 完整代码:参数解析+CARLA连接+地图加载 -if __name__ == "__main__": +# 全局变量:存储生成的CARLA Actor(车辆、传感器等),用于退出时清理 +generated_actors = [] + +def main(): # 1. 解析命令行参数(带输入校验) parser = argparse.ArgumentParser(description='CVIPS场景数据生成工具') parser.add_argument('--town', type=str, required=True, choices=['Town04', 'Town10HD', 'Town07'], @@ -16,12 +19,117 @@ help='时段(noon=中午,sunset=日落,night=夜晚)') args = parser.parse_args() + # 2. 连接CARLA服务器(带重试机制) + client, world = connect_carla_with_retry(args.town) + if not world: + return # 连接失败直接退出 + + # 3. 配置天气和时段(让参数实际生效) + configure_weather_and_time(world, args.weather, args.time_of_day) + + # 4. 基于路口类型生成场景(预留核心逻辑,可根据需求扩展) + generate_intersection_scene(world, args.intersection) + + # 5. 保持场景运行(按 Ctrl+C 退出并清理资源) + print("\n🚗 场景已启动!按 Ctrl+C 退出并清理资源...") try: - # 2. 连接CARLA服务器(设置超时重试机制) - client = carla.Client('localhost', 2000) - client.set_timeout(15.0) - client.load_world(args.town) # 加载指定城镇 - world = client.get_world() - print(f"✅ 成功连接CARLA并加载地图:{args.town}") - except Exception as e: - print(f"❌ 连接失败:{str(e)},请检查CARLA服务器是否启动") \ No newline at end of file + while True: + time.sleep(1) + except KeyboardInterrupt: + print("\n🛑 收到退出信号,开始清理资源...") + +# ------------------------------ 辅助函数 ------------------------------ +def connect_carla_with_retry(town_name, max_retries=3, retry_interval=5): + """带重试机制的CARLA连接函数""" + client = None + world = None + for retry in range(max_retries): + try: + client = carla.Client('localhost', 2000) + client.set_timeout(15.0) + client.load_world(town_name) # 加载指定地图 + world = client.get_world() + print(f"✅ 成功连接CARLA并加载地图:{town_name}") + return client, world + except Exception as e: + error_msg = str(e) + if retry < max_retries - 1: + print(f"❌ 连接失败({retry+1}/{max_retries}):{error_msg}") + print(f"⌛ {retry_interval}秒后重试...") + time.sleep(retry_interval) + else: + print(f"❌ 连接失败(已达最大重试次数):{error_msg}") + print("💡 请检查:1. CARLA服务器是否启动 2. 端口是否为2000 3. 地图名称是否正确") + return None, None + +def configure_weather_and_time(world, weather_type, time_of_day): + """配置CARLA的天气和时段(让命令行参数生效)""" + # CARLA预设天气映射(对应自定义参数) + base_weather_mapping = { + 'clear': carla.WeatherParameters.ClearNoon, + 'rainy': carla.WeatherParameters.RainyNoon, + 'cloudy': carla.WeatherParameters.CloudyNoon + } + + # 获取基础天气参数并根据时段调整 + weather = base_weather_mapping[weather_type] + if time_of_day == 'sunset': + weather.sun_altitude_angle = -15.0 # 日落:太阳高度角为负(地平线以下) + weather.ambient_light = 0.3 # 降低环境光强度 + weather.directional_light_intensity = 0.5 # 降低直射光强度 + weather.fog_density = 0.1 # 日落添加轻微雾气 + elif time_of_day == 'night': + weather.sun_altitude_angle = -60.0 # 夜晚:太阳高度角极低 + weather.ambient_light = 0.05 # 极低环境光 + weather.directional_light_intensity = 0.01 # 几乎无直射光 + weather.moon_altitude_angle = 45.0 # 月亮高度角 + weather.moon_intensity = 0.8 # 月亮亮度 + weather.stars_intensity = 0.5 # 星星亮度 + # noon(中午):使用默认预设,无需额外调整 + + # 应用天气设置 + world.set_weather(weather) + print(f"✅ 已配置环境:天气={weather_type},时段={time_of_day}") + +def generate_intersection_scene(world, intersection_type): + """基于路口类型生成场景(核心逻辑,可扩展)""" + print(f"📌 开始生成{intersection_type}路口场景...") + + # ------------------------------ + # 此处为预留逻辑,可根据需求扩展: + # 1. 定位地图中对应类型的路口坐标(需提前调研目标地图的路口位置) + # 2. 在路口周围生成车辆、行人、红绿灯等Actor + # 3. 设置车辆行驶路线、交通规则等 + # ------------------------------ + example_spawn_point = get_example_spawn_point(world) + if example_spawn_point: + # 示例:生成1辆测试车辆(添加到全局列表,方便退出时清理) + vehicle_bp = world.get_blueprint_library().find('vehicle.tesla.model3') + vehicle = world.spawn_actor(vehicle_bp, example_spawn_point) + generated_actors.append(vehicle) + print(f"✅ 已在路口附近生成测试车辆(ID:{vehicle.id})") + else: + print("⚠️ 未找到合适的车辆生成点,路口场景生成失败") + +def get_example_spawn_point(world): + """获取示例生成点(可根据实际地图路口位置修改)""" + spawn_points = world.get_map().get_spawn_points() + # 取前10个生成点中的第3个作为示例(可根据地图路口位置调整索引) + return spawn_points[2] if len(spawn_points) > 2 else None + +def clean_up_actors(): + """退出时清理所有生成的Actor(车辆、传感器等)""" + if generated_actors: + print(f"🧹 正在清理 {len(generated_actors)} 个仿真对象...") + for actor in generated_actors: + if actor.is_alive: + actor.destroy() + print("✅ 资源清理完成!") + else: + print("✅ 无需要清理的仿真对象") + +# 注册退出回调:程序终止时自动清理资源 +atexit.register(clean_up_actors) + +if __name__ == "__main__": + main() \ No newline at end of file From 672201b4c4c8f13ff82d292b40592e94e7328eb2 Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Thu, 20 Nov 2025 11:24:28 +0800 Subject: [PATCH 18/34] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=BB=88=E7=AB=AF?= =?UTF-8?q?=E5=91=BD=E4=BB=A4=E8=AF=B4=E6=98=8E=E5=92=8C=E9=A1=B9=E7=9B=AE?= =?UTF-8?q?=E4=BE=9D=E8=B5=96=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/InterconVis_PedSafety_Enh/Terminal_Commands.txt | 11 +++++++++++ src/InterconVis_PedSafety_Enh/requirements.txt | 5 +++++ 2 files changed, 16 insertions(+) create mode 100644 src/InterconVis_PedSafety_Enh/Terminal_Commands.txt create mode 100644 src/InterconVis_PedSafety_Enh/requirements.txt diff --git a/src/InterconVis_PedSafety_Enh/Terminal_Commands.txt b/src/InterconVis_PedSafety_Enh/Terminal_Commands.txt new file mode 100644 index 0000000000..56726ea4aa --- /dev/null +++ b/src/InterconVis_PedSafety_Enh/Terminal_Commands.txt @@ -0,0 +1,11 @@ +# 测试1:基础场景(Town04+4岔路口+晴天+中午) +python cvips_generation.py --town Town04 --intersection 4way --weather clear --time_of_day noon + +# 测试2:复杂场景(Town10HD+3岔路口+雨天+日落+高行人密度) +python cvips_generation.py --town Town10HD --intersection 3way --weather rainy --time_of_day sunset --crowd_level high --crossing_percentage 0.3 + +# 测试3:夜间场景(Town07+4岔路口+阴天+夜间+自定义随机种子) +python cvips_generation.py --town Town07 --intersection 4way --weather cloudy --time_of_day night --seed_value 123 --scenario scenario00005 + +# 测试4:最简场景(Town04+3岔路口+晴天+日落) +python cvips_generation.py --town Town04 --intersection 3way --weather clear --time_of_day sunset \ No newline at end of file diff --git a/src/InterconVis_PedSafety_Enh/requirements.txt b/src/InterconVis_PedSafety_Enh/requirements.txt new file mode 100644 index 0000000000..8651856a79 --- /dev/null +++ b/src/InterconVis_PedSafety_Enh/requirements.txt @@ -0,0 +1,5 @@ +carla==0.9.14 +pygame==2.1.0 +numpy==1.21.5 +Pillow==9.2.0 +icecream==2.1.3 \ No newline at end of file From b2da81079f9ede0a992663252b605d10da54a363 Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Thu, 20 Nov 2025 15:05:04 +0800 Subject: [PATCH 19/34] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=8C=87=E4=BB=A4?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E6=A0=BC=E5=BC=8F=EF=BC=8C=E4=BF=AE=E6=94=B9?= =?UTF-8?q?=E8=BF=90=E8=A1=8C=E6=96=87=E4=BB=B6(=E4=B9=8B=E5=89=8D?= =?UTF-8?q?=E7=9A=84=E4=BB=A3=E7=A0=81=E4=BF=9D=E5=AD=98=E4=B8=8D=E6=88=90?= =?UTF-8?q?=E5=8A=9F)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Terminal_Commands.md | 16 ++++ .../cvips_generation.py | 75 ++++++++++--------- 2 files changed, 56 insertions(+), 35 deletions(-) create mode 100644 src/InterconVis_PedSafety_Enh/Terminal_Commands.md diff --git a/src/InterconVis_PedSafety_Enh/Terminal_Commands.md b/src/InterconVis_PedSafety_Enh/Terminal_Commands.md new file mode 100644 index 0000000000..2e6bc226d4 --- /dev/null +++ b/src/InterconVis_PedSafety_Enh/Terminal_Commands.md @@ -0,0 +1,16 @@ +# 测试1:基础场景(Town04+4岔路口+晴天+中午) +```shell +python cvips_generation.py --town Town04 --intersection 4way --weather clear --time_of_day noon +``` +# 测试2:复杂场景(Town10HD+3岔路口+雨天+日落+高行人密度) +```shell +python cvips_generation.py --town Town10HD --intersection 3way --weather rainy --time_of_day sunset --crowd_level high --crossing_percentage 0.3 +``` +# 测试3:夜间场景(Town07+4岔路口+阴天+夜间+自定义随机种子) +```shell +python cvips_generation.py --town Town07 --intersection 4way --weather cloudy --time_of_day night --seed_value 123 --scenario scenario00005 +``` +# 测试4:最简场景(Town04+3岔路口+晴天+日落) +```shell +python cvips_generation.py --town Town04 --intersection 3way --weather clear --time_of_day sunset +``` \ No newline at end of file diff --git a/src/InterconVis_PedSafety_Enh/cvips_generation.py b/src/InterconVis_PedSafety_Enh/cvips_generation.py index 223b86f448..0448f7124d 100644 --- a/src/InterconVis_PedSafety_Enh/cvips_generation.py +++ b/src/InterconVis_PedSafety_Enh/cvips_generation.py @@ -27,7 +27,7 @@ def main(): # 3. 配置天气和时段(让参数实际生效) configure_weather_and_time(world, args.weather, args.time_of_day) - # 4. 基于路口类型生成场景(预留核心逻辑,可根据需求扩展) + # 4. 基于路口类型生成场景(基础逻辑) generate_intersection_scene(world, args.intersection) # 5. 保持场景运行(按 Ctrl+C 退出并清理资源) @@ -63,47 +63,53 @@ def connect_carla_with_retry(town_name, max_retries=3, retry_interval=5): return None, None def configure_weather_and_time(world, weather_type, time_of_day): - """配置CARLA的天气和时段(让命令行参数生效)""" - # CARLA预设天气映射(对应自定义参数) - base_weather_mapping = { - 'clear': carla.WeatherParameters.ClearNoon, - 'rainy': carla.WeatherParameters.RainyNoon, - 'cloudy': carla.WeatherParameters.CloudyNoon - } - - # 获取基础天气参数并根据时段调整 - weather = base_weather_mapping[weather_type] - if time_of_day == 'sunset': - weather.sun_altitude_angle = -15.0 # 日落:太阳高度角为负(地平线以下) - weather.ambient_light = 0.3 # 降低环境光强度 - weather.directional_light_intensity = 0.5 # 降低直射光强度 - weather.fog_density = 0.1 # 日落添加轻微雾气 + """配置CARLA的天气和时段(细化不同天气-时段的环境参数)""" + # 初始化天气参数 + weather = carla.WeatherParameters() + + # 配置天气类型 + if weather_type == 'clear': + weather.cloudiness = 0.0 + weather.precipitation = 0.0 + elif weather_type == 'rainy': + weather.cloudiness = 80.0 + weather.precipitation = 50.0 + weather.precipitation_deposits = 30.0 + weather.wind_intensity = 10.0 # 雨天增加风力 + elif weather_type == 'cloudy': + weather.cloudiness = 70.0 + weather.precipitation = 0.0 + weather.fog_density = 0.2 # 阴天增加雾气 + + # 配置时段(通过太阳高度角、环境光等参数) + if time_of_day == 'noon': + weather.sun_altitude_angle = 90.0 # 正午太阳高度角 + weather.ambient_light = 1.0 + weather.directional_light_intensity = 2.0 + elif time_of_day == 'sunset': + weather.sun_altitude_angle = -15.0 # 日落太阳高度角(地平线以下) + weather.ambient_light = 0.3 + weather.directional_light_intensity = 0.5 + weather.fog_density = 0.1 # 日落雾气 elif time_of_day == 'night': - weather.sun_altitude_angle = -60.0 # 夜晚:太阳高度角极低 - weather.ambient_light = 0.05 # 极低环境光 - weather.directional_light_intensity = 0.01 # 几乎无直射光 - weather.moon_altitude_angle = 45.0 # 月亮高度角 - weather.moon_intensity = 0.8 # 月亮亮度 - weather.stars_intensity = 0.5 # 星星亮度 - # noon(中午):使用默认预设,无需额外调整 - + weather.sun_altitude_angle = -60.0 # 夜间太阳高度角 + weather.ambient_light = 0.05 + weather.directional_light_intensity = 0.01 + weather.moon_altitude_angle = 45.0 # 月亮高度角 + weather.moon_intensity = 0.8 # 月亮亮度 + weather.stars_intensity = 0.5 # 星星亮度 + # 应用天气设置 world.set_weather(weather) print(f"✅ 已配置环境:天气={weather_type},时段={time_of_day}") def generate_intersection_scene(world, intersection_type): - """基于路口类型生成场景(核心逻辑,可扩展)""" + """基于路口类型生成基础场景(可后续扩展)""" print(f"📌 开始生成{intersection_type}路口场景...") - # ------------------------------ - # 此处为预留逻辑,可根据需求扩展: - # 1. 定位地图中对应类型的路口坐标(需提前调研目标地图的路口位置) - # 2. 在路口周围生成车辆、行人、红绿灯等Actor - # 3. 设置车辆行驶路线、交通规则等 - # ------------------------------ example_spawn_point = get_example_spawn_point(world) if example_spawn_point: - # 示例:生成1辆测试车辆(添加到全局列表,方便退出时清理) + # 示例:生成1辆测试车辆 vehicle_bp = world.get_blueprint_library().find('vehicle.tesla.model3') vehicle = world.spawn_actor(vehicle_bp, example_spawn_point) generated_actors.append(vehicle) @@ -112,13 +118,12 @@ def generate_intersection_scene(world, intersection_type): print("⚠️ 未找到合适的车辆生成点,路口场景生成失败") def get_example_spawn_point(world): - """获取示例生成点(可根据实际地图路口位置修改)""" + """获取示例生成点""" spawn_points = world.get_map().get_spawn_points() - # 取前10个生成点中的第3个作为示例(可根据地图路口位置调整索引) return spawn_points[2] if len(spawn_points) > 2 else None def clean_up_actors(): - """退出时清理所有生成的Actor(车辆、传感器等)""" + """退出时清理所有生成的Actor""" if generated_actors: print(f"🧹 正在清理 {len(generated_actors)} 个仿真对象...") for actor in generated_actors: From 2197eeb7c58886301c2c5212e2755f9e01164641 Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Thu, 20 Nov 2025 15:25:25 +0800 Subject: [PATCH 20/34] =?UTF-8?q?=E6=9B=B4=E6=94=B9=E6=8C=87=E4=BB=A4?= =?UTF-8?q?=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Terminal_Commands.md | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/InterconVis_PedSafety_Enh/Terminal_Commands.md b/src/InterconVis_PedSafety_Enh/Terminal_Commands.md index 2e6bc226d4..0908add989 100644 --- a/src/InterconVis_PedSafety_Enh/Terminal_Commands.md +++ b/src/InterconVis_PedSafety_Enh/Terminal_Commands.md @@ -1,16 +1,23 @@ -# 测试1:基础场景(Town04+4岔路口+晴天+中午) +# 1. 基础场景:各地图+路口类型验证 ```shell python cvips_generation.py --town Town04 --intersection 4way --weather clear --time_of_day noon +python cvips_generation.py --town Town10HD --intersection 3way --weather clear --time_of_day sunset +python cvips_generation.py --town Town07 --intersection 4way --weather cloudy --time_of_day noon ``` -# 测试2:复杂场景(Town10HD+3岔路口+雨天+日落+高行人密度) +# 2. 天气+时段组合场景(覆盖所有环境组合) ```shell -python cvips_generation.py --town Town10HD --intersection 3way --weather rainy --time_of_day sunset --crowd_level high --crossing_percentage 0.3 +python cvips_generation.py --town Town04 --intersection 3way --weather rainy --time_of_day night +python cvips_generation.py --town Town10HD --intersection 4way --weather cloudy --time_of_day sunset +python cvips_generation.py --town Town07 --intersection 3way --weather clear --time_of_day night +python cvips_generation.py --town Town04 --intersection 4way --weather rainy --time_of_day noon ``` -# 测试3:夜间场景(Town07+4岔路口+阴天+夜间+自定义随机种子) +# 3. 边界场景(极限环境测试) ```shell -python cvips_generation.py --town Town07 --intersection 4way --weather cloudy --time_of_day night --seed_value 123 --scenario scenario00005 +python cvips_generation.py --town Town10HD --intersection 4way --weather rainy --time_of_day night +python cvips_generation.py --town Town07 --intersection 3way --weather cloudy --time_of_day night ``` -# 测试4:最简场景(Town04+3岔路口+晴天+日落) +# 4. 常用场景快捷指令 ```shell -python cvips_generation.py --town Town04 --intersection 3way --weather clear --time_of_day sunset +python cvips_generation.py --town Town04 --intersection 3way --weather clear --time_of_day noon +python cvips_generation.py --town Town10HD --intersection 4way --weather clear --time_of_day sunset ``` \ No newline at end of file From d69375b0bf052f00a07b020ae468151a302b596b Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Mon, 24 Nov 2025 10:25:33 +0800 Subject: [PATCH 21/34] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=BD=A6=E8=BE=86?= =?UTF-8?q?=E5=AF=B9=E8=B1=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cvips_generation.py | 158 +++++++++--------- 1 file changed, 83 insertions(+), 75 deletions(-) diff --git a/src/InterconVis_PedSafety_Enh/cvips_generation.py b/src/InterconVis_PedSafety_Enh/cvips_generation.py index 0448f7124d..df65e44881 100644 --- a/src/InterconVis_PedSafety_Enh/cvips_generation.py +++ b/src/InterconVis_PedSafety_Enh/cvips_generation.py @@ -2,35 +2,45 @@ import argparse import time import atexit +import random -# 全局变量:存储生成的CARLA Actor(车辆、传感器等),用于退出时清理 +# 全局变量 generated_actors = [] +client = None +world = None def main(): - # 1. 解析命令行参数(带输入校验) - parser = argparse.ArgumentParser(description='CVIPS场景数据生成工具') - parser.add_argument('--town', type=str, required=True, choices=['Town04', 'Town10HD', 'Town07'], - help='CARLA城镇地图(支持:Town04/Town10HD/Town07)') - parser.add_argument('--intersection', type=str, required=True, choices=['3way', '4way'], - help='路口类型(3way=三叉路口,4way=四岔路口)') - parser.add_argument('--weather', type=str, required=True, choices=['clear', 'rainy', 'cloudy'], - help='天气条件(clear=晴天,rainy=雨天,cloudy=阴天)') - parser.add_argument('--time_of_day', type=str, required=True, choices=['noon', 'sunset', 'night'], - help='时段(noon=中午,sunset=日落,night=夜晚)') + global client, world + + parser = argparse.ArgumentParser(description='CARLA 0.9.14 车辆生成工具 (支持环境配置)') + parser.add_argument('--town', type=str, required=True, help='城镇地图 (例如: Town04)') + parser.add_argument('--num_vehicles', type=int, default=10, help='生成车辆数量') + parser.add_argument('--seed', type=int, default=None, help='随机种子') + # 新增环境参数 + parser.add_argument('--weather', type=str, default='clear', choices=['clear', 'rainy', 'cloudy'], help='天气类型') + parser.add_argument('--time_of_day', type=str, default='noon', choices=['noon', 'sunset', 'night'], help='时段') args = parser.parse_args() - # 2. 连接CARLA服务器(带重试机制) + # 设置随机种子 + if args.seed is not None: + random.seed(args.seed) + print(f"✅ 已设置随机种子: {args.seed}") + + # 连接 CARLA client, world = connect_carla_with_retry(args.town) if not world: - return # 连接失败直接退出 + return - # 3. 配置天气和时段(让参数实际生效) + # --- 新增代码:配置天气和时间 --- + print("\n🌤️ 正在配置环境...") configure_weather_and_time(world, args.weather, args.time_of_day) - # 4. 基于路口类型生成场景(基础逻辑) - generate_intersection_scene(world, args.intersection) + # 生成车辆 + print("\n📌 开始生成场景...") + generate_vehicles(world, args.num_vehicles) + print("\n✅ 场景生成完毕!") - # 5. 保持场景运行(按 Ctrl+C 退出并清理资源) + # 保持运行 print("\n🚗 场景已启动!按 Ctrl+C 退出并清理资源...") try: while True: @@ -39,101 +49,99 @@ def main(): print("\n🛑 收到退出信号,开始清理资源...") # ------------------------------ 辅助函数 ------------------------------ + def connect_carla_with_retry(town_name, max_retries=3, retry_interval=5): - """带重试机制的CARLA连接函数""" - client = None - world = None + """带重试机制的 CARLA 连接函数""" + global client for retry in range(max_retries): try: client = carla.Client('localhost', 2000) client.set_timeout(15.0) - client.load_world(town_name) # 加载指定地图 + client.load_world(town_name) world = client.get_world() - print(f"✅ 成功连接CARLA并加载地图:{town_name}") + print(f"✅ 成功连接 CARLA 并加载地图:{town_name}") return client, world except Exception as e: error_msg = str(e) if retry < max_retries - 1: - print(f"❌ 连接失败({retry+1}/{max_retries}):{error_msg}") + print(f"❌ 连接失败({retry + 1}/{max_retries}):{error_msg}") print(f"⌛ {retry_interval}秒后重试...") time.sleep(retry_interval) else: print(f"❌ 连接失败(已达最大重试次数):{error_msg}") - print("💡 请检查:1. CARLA服务器是否启动 2. 端口是否为2000 3. 地图名称是否正确") + print("💡 请检查:1. CARLA 服务器是否启动 2. 端口是否为 2000") return None, None +# --- 新增函数:配置天气和时间 --- def configure_weather_and_time(world, weather_type, time_of_day): - """配置CARLA的天气和时段(细化不同天气-时段的环境参数)""" - # 初始化天气参数 + """配置 CARLA 的天气和时段""" weather = carla.WeatherParameters() - # 配置天气类型 if weather_type == 'clear': - weather.cloudiness = 0.0 - weather.precipitation = 0.0 + weather.cloudiness = 0; weather.precipitation = 0 elif weather_type == 'rainy': - weather.cloudiness = 80.0 - weather.precipitation = 50.0 - weather.precipitation_deposits = 30.0 - weather.wind_intensity = 10.0 # 雨天增加风力 + weather.cloudiness = 80; weather.precipitation = 50; weather.precipitation_deposits = 30; weather.wind_intensity = 10; weather.fog_density = 0.3 elif weather_type == 'cloudy': - weather.cloudiness = 70.0 - weather.precipitation = 0.0 - weather.fog_density = 0.2 # 阴天增加雾气 - - # 配置时段(通过太阳高度角、环境光等参数) + weather.cloudiness = 70; weather.precipitation = 0; weather.fog_density = 0.2 + if time_of_day == 'noon': - weather.sun_altitude_angle = 90.0 # 正午太阳高度角 - weather.ambient_light = 1.0 - weather.directional_light_intensity = 2.0 + weather.sun_altitude_angle = 90; weather.ambient_light = 1.0 elif time_of_day == 'sunset': - weather.sun_altitude_angle = -15.0 # 日落太阳高度角(地平线以下) - weather.ambient_light = 0.3 - weather.directional_light_intensity = 0.5 - weather.fog_density = 0.1 # 日落雾气 + weather.sun_altitude_angle = -15; weather.ambient_light = 0.3 elif time_of_day == 'night': - weather.sun_altitude_angle = -60.0 # 夜间太阳高度角 - weather.ambient_light = 0.05 - weather.directional_light_intensity = 0.01 - weather.moon_altitude_angle = 45.0 # 月亮高度角 - weather.moon_intensity = 0.8 # 月亮亮度 - weather.stars_intensity = 0.5 # 星星亮度 + weather.sun_altitude_angle = -60; weather.ambient_light = 0.05; weather.moon_altitude_angle = 45; weather.moon_intensity = 0.8 - # 应用天气设置 world.set_weather(weather) print(f"✅ 已配置环境:天气={weather_type},时段={time_of_day}") -def generate_intersection_scene(world, intersection_type): - """基于路口类型生成基础场景(可后续扩展)""" - print(f"📌 开始生成{intersection_type}路口场景...") - - example_spawn_point = get_example_spawn_point(world) - if example_spawn_point: - # 示例:生成1辆测试车辆 - vehicle_bp = world.get_blueprint_library().find('vehicle.tesla.model3') - vehicle = world.spawn_actor(vehicle_bp, example_spawn_point) - generated_actors.append(vehicle) - print(f"✅ 已在路口附近生成测试车辆(ID:{vehicle.id})") - else: - print("⚠️ 未找到合适的车辆生成点,路口场景生成失败") +def generate_vehicles(world, num_vehicles): + """生成指定数量的车辆并开启自动驾驶 (CARLA 0.9.14 兼容)""" + if num_vehicles <= 0: + print("ℹ️ 车辆数量为 0,不生成车辆。") + return -def get_example_spawn_point(world): - """获取示例生成点""" spawn_points = world.get_map().get_spawn_points() - return spawn_points[2] if len(spawn_points) > 2 else None + if not spawn_points: + print("⚠️ 未找到车辆生成点。") + return + + vehicle_bps = world.get_blueprint_library().filter('vehicle.*') + tm = client.get_trafficmanager(8000) + tm.set_global_distance_to_leading_vehicle(2.5) + + print(f"🚗 正在生成 {num_vehicles} 辆车辆...") + for i in range(num_vehicles): + spawn_point = random.choice(spawn_points) + vehicle_bp = random.choice(vehicle_bps) + + # 通过蓝图设置最大速度 (CARLA 0.9.14 兼容方式) + try: + max_speed_kmh = random.uniform(25, 35) + vehicle_bp.set_attribute('speed', str(max_speed_kmh / 3.6)) + except Exception: + pass # 忽略不支持此属性的车辆 + + vehicle = world.try_spawn_actor(vehicle_bp, spawn_point) + if vehicle: + generated_actors.append(vehicle) + vehicle.set_autopilot(True, tm.get_port()) + + num_generated = len([a for a in generated_actors if a.type_id.startswith('vehicle')]) + print(f"✅ 成功生成 {num_generated} 辆车辆。") def clean_up_actors(): - """退出时清理所有生成的Actor""" + """退出时清理所有生成的 Actor""" + global client if generated_actors: - print(f"🧹 正在清理 {len(generated_actors)} 个仿真对象...") - for actor in generated_actors: - if actor.is_alive: - actor.destroy() + print(f"\n🧹 正在清理 {len(generated_actors)} 个仿真对象...") + batch = [carla.command.DestroyActor(x) for x in generated_actors] + if client: + client.apply_batch(batch) + generated_actors.clear() print("✅ 资源清理完成!") else: - print("✅ 无需要清理的仿真对象") + print("\n✅ 无需要清理的仿真对象。") -# 注册退出回调:程序终止时自动清理资源 atexit.register(clean_up_actors) if __name__ == "__main__": From ac1fb5837d4ba611c020c150127c532ed36714e6 Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Mon, 24 Nov 2025 11:38:11 +0800 Subject: [PATCH 22/34] =?UTF-8?q?=E6=9B=B4=E6=96=B0README.md=E5=92=8CComma?= =?UTF-8?q?nds=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/InterconVis_PedSafety_Enh/README.md | 124 +++++++----------- .../Terminal_Commands.md | 31 ++--- 2 files changed, 64 insertions(+), 91 deletions(-) diff --git a/src/InterconVis_PedSafety_Enh/README.md b/src/InterconVis_PedSafety_Enh/README.md index afbc3105da..c4cbc54a47 100644 --- a/src/InterconVis_PedSafety_Enh/README.md +++ b/src/InterconVis_PedSafety_Enh/README.md @@ -1,113 +1,85 @@ -# CVIPS: Connected Vision for Increased Pedestrian Safety -Implementation of the CVIPS project. -- [X] Dataset -- [X] CARLA data generation code +#CVIPS: 面向提升行人安全的协同视觉 (Connected Vision for Increased Pedestrian Safety) +CVIPS 项目的实现。 +- [X] 数据集 +- [X] CARLA 数据生成代码 -## Dataset -The CVIPS dataset is available [here](https://drive.google.com/drive/folders/1gCCrIslzVkupyF0lj_1I9qXTB2_a4tjd?usp=drive_link). +## 数据集 (Dataset) +CVIPS 数据集可在此处获取:[here](https://drive.google.com/drive/folders/1gCCrIslzVkupyF0lj_1I9qXTB2_a4tjd?usp=drive_link). -## Installation -Please check [installation](https://carla.readthedocs.io/en/0.9.14/build_windows) on how to setup CARLA for windows +## 安装 (Installation) +请参考 [installation](https://carla.readthedocs.io/en/0.9.14/build_windows) 了解如何在 Windows 上设置 CARLA。 +## 数据集生成 (Dataset Generation) +我们的数据集是使用 CARLA 模拟器生成的,为协同感知提供了多样化的场景。 +###运行数据生成脚本 (Running the Data Generation Script) -## Dataset Generation -Our dataset is generated using the CARLA simulator, providing diverse scenarios for collaborative perception. - -### Running the Data Generation Script - -1. Clone the repository: +1. 克隆此仓库 ``` git clone https://github.com/cvips/CVIPS.git cd CVIPS ``` -2. Install the required dependencies: +2. 安装所需的依赖包: ``` pip install -r requirements.txt ``` -3. Ensure CARLA is properly installed and running. Start the CARLA server in a separate terminal: +3. 确保 CARLA 已正确安装并运行。在一个单独的终端中启动 CARLA 服务器: ``` /path/to/carla/CarlaUE4.exe ``` -4. Run the data generation script: +4. 运行数据生成脚本: ``` python cvips_generation.py ``` - This script will connect to the CARLA server and generate the dataset based on the specified parameters. - -Note: Make sure to adjust the CARLA server path and any configuration parameters in `cvips_generation.py` as needed for your specific setup. - + 该脚本将连接到 CARLA 服务器,并根据指定的参数生成数据集。 +注意:请根据你特定的设置需求,调整 cvips_generation.py 中的 CARLA 服务器路径以及任何配置参数。 ### Sample Examples -Here are some example commands to generate different scenarios: - -1. Four-way intersection in Town10HD with clear weather at noon: - ``` - python cvips_generation.py --town Town10HD --intersection 4way --setup wsee --weather clear --time_of_the_day noon --crowd_level medium --crossing_percentage 0.1 --seed_value 23 --scenario scenario00001 - ``` - -2. Four-way intersection in Town04 with rainy weather at sunset: - ``` - python cvips_generation.py --town Town04 --intersection 4way --setup wwss --weather rainy --time_of_the_day sunset --crowd_level medium --crossing_percentage 0.1 --seed_value 42 --scenario scenario00002 - ``` - -3. Three-way intersection in Town05 with clear weather at night: - ``` - python cvips_generation.py --town Town05 --intersection 3way --setup wwss --weather clear --time_of_the_day night --crowd_level medium --crossing_percentage 0.1 --seed_value 73 --scenario scenario00005 - ``` - -4. Four-way intersection in Town10HD with cloudy weather at noon: - ``` - python cvips_generation.py --town Town10HD --intersection 4way --setup wwws --weather cloudy --time_of_the_day noon --crowd_level medium --crossing_percentage 0.1 --seed_value 101 --scenario scenario00011 - ``` - -These examples demonstrate various combinations of towns, intersection types, weather conditions, times of day, and camera setups. Users can modify these parameters to generate different scenarios as needed. - -### Sample Visualizations - -We provide visualizations to demonstrate different perspectives in our dataset: -(this can be done using [Code/data_viz.py](Code\data_viz.py)) -1. **Infrastructure View** (6 cameras) - Infrastructure View - This visualization shows the scene from fixed infrastructure cameras, providing a comprehensive view of the intersection from multiple angles. - -2. **Vehicle View** (6 cameras) - Vehicle View - This visualization demonstrates the perspective from a moving vehicle, showcasing the view from various angles around the vehicle. - -3. **Collaborative View** (4 cameras) - Collaborative View - This visualization combines views from both vehicles and infrastructure, illustrating the collaborative perception aspect of our dataset. - - -- Multiple camera perspectives (infrastructure, vehicle-mounted, and collaborative) -- Various weather conditions and times of day () -- Diverse traffic scenarios with multiple vehicles and pedestrians setup (controlled by seeds, number of pedestrians, number of vehicles to be spawned) - +#示例命令 (Sample Examples) +# 1. 默认配置:在 Town04 生成 10 辆车辆,天气为晴天,时间为中午 +```shell +python generate_vehicles_only.py --town Town04 +``` +# 2. 自定义车辆数量:在 Town04 生成 15 辆车辆 +```shell +python generate_vehicles_only.py --town Town04 --num_vehicles 15 +``` +# 3. 自定义天气:在 Town04 生成 10 辆车辆,天气为雨天 +```shell +python generate_vehicles_only.py --town Town04 --weather rainy +``` +# 4. 自定义时间:在 Town04 生成 10 辆车辆,时间为夜晚 +```shell +python generate_vehicles_only.py --town Town04 --time_of_day night +``` +# 5. 完整自定义:在 Town07 生成 20 辆车辆,天气为多云,时间为日落 +```shell +python generate_vehicles_only.py --town Town07 --num_vehicles 20 --weather cloudy --time_of_day sunset +``` +# 6. 设置随机种子(保证场景可复现):在 Town10HD 生成 12 辆车辆,使用种子 123 +```shell +python generate_vehicles_only.py --town Town10HD --num_vehicles 12 --seed 123 +``` +这些示例展示了城镇、交叉路口类型、天气状况、时间段,车辆和摄像头设置的各种组合。用户可以根据需要修改这些参数以生成不同的场景。 -## For Detection in collaborative setup check the documentation of V2XFormer -First, prepare the dataset with this format [data_preparation](docs/data_preparation.md) . -Then, use [V2XFormer](https://github.com/tianqi-wang1996/DeepAccident) according to the instructions here -1. [Installation](https://github.com/tianqi-wang1996/DeepAccident/blob/main/docs/installation.md) -2. [Training and Evaluation](https://github.com/tianqi-wang1996/DeepAccident/blob/main/docs/getting_started.md) -- adjust the datapaths and number of classes accordingly - -## Acknowledgement -This project is based on the following open-source projects: [BEVerse](https://github.com/zhangyp15/BEVerse), [Fiery](https://github.com/wayveai/fiery), [open-mmlab](https://github.com/open-mmlab), and [DeepAccident](https://arxiv.org/pdf/2304.01168). +### 样本可视化 (Sample Visualizations) -## Citation +我们提供了可视化结果来展示我们数据集中的不同视角: +![动图加载失败](images/2025-11-24102317-ezgif.com-speed.gif "车辆环境演示1") +## 致谢 (Acknowledgement) +本项目基于以下开源项目: BEVerse, Fiery, open-mmlab, 以及 DeepAccident。 -``` diff --git a/src/InterconVis_PedSafety_Enh/Terminal_Commands.md b/src/InterconVis_PedSafety_Enh/Terminal_Commands.md index 0908add989..58ca64a9ba 100644 --- a/src/InterconVis_PedSafety_Enh/Terminal_Commands.md +++ b/src/InterconVis_PedSafety_Enh/Terminal_Commands.md @@ -1,23 +1,24 @@ -# 1. 基础场景:各地图+路口类型验证 +# 1. 默认配置:在 Town04 生成 10 辆车辆,天气为晴天,时间为中午 ```shell -python cvips_generation.py --town Town04 --intersection 4way --weather clear --time_of_day noon -python cvips_generation.py --town Town10HD --intersection 3way --weather clear --time_of_day sunset -python cvips_generation.py --town Town07 --intersection 4way --weather cloudy --time_of_day noon +python generate_vehicles_only.py --town Town04 ``` -# 2. 天气+时段组合场景(覆盖所有环境组合) +# 2. 自定义车辆数量:在 Town04 生成 15 辆车辆 ```shell -python cvips_generation.py --town Town04 --intersection 3way --weather rainy --time_of_day night -python cvips_generation.py --town Town10HD --intersection 4way --weather cloudy --time_of_day sunset -python cvips_generation.py --town Town07 --intersection 3way --weather clear --time_of_day night -python cvips_generation.py --town Town04 --intersection 4way --weather rainy --time_of_day noon +python generate_vehicles_only.py --town Town04 --num_vehicles 15 ``` -# 3. 边界场景(极限环境测试) +# 3. 自定义天气:在 Town04 生成 10 辆车辆,天气为雨天 ```shell -python cvips_generation.py --town Town10HD --intersection 4way --weather rainy --time_of_day night -python cvips_generation.py --town Town07 --intersection 3way --weather cloudy --time_of_day night +python generate_vehicles_only.py --town Town04 --weather rainy ``` -# 4. 常用场景快捷指令 +# 4. 自定义时间:在 Town04 生成 10 辆车辆,时间为夜晚 ```shell -python cvips_generation.py --town Town04 --intersection 3way --weather clear --time_of_day noon -python cvips_generation.py --town Town10HD --intersection 4way --weather clear --time_of_day sunset +python generate_vehicles_only.py --town Town04 --time_of_day night +``` +# 5. 完整自定义:在 Town07 生成 20 辆车辆,天气为多云,时间为日落 +```shell +python generate_vehicles_only.py --town Town07 --num_vehicles 20 --weather cloudy --time_of_day sunset +``` +# 6. 设置随机种子(保证场景可复现):在 Town10HD 生成 12 辆车辆,使用种子 123 +```shell +python generate_vehicles_only.py --town Town10HD --num_vehicles 12 --seed 123 ``` \ No newline at end of file From 39588aaff8a3c7570cb23d6440f35cac4fc08c5e Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Wed, 26 Nov 2025 10:24:50 +0800 Subject: [PATCH 23/34] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=A1=8C=E4=BA=BA?= =?UTF-8?q?=E5=AF=B9=E8=B1=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cvips_generation.py | 100 +++++++++++++----- 1 file changed, 74 insertions(+), 26 deletions(-) diff --git a/src/InterconVis_PedSafety_Enh/cvips_generation.py b/src/InterconVis_PedSafety_Enh/cvips_generation.py index df65e44881..fdeb2492b2 100644 --- a/src/InterconVis_PedSafety_Enh/cvips_generation.py +++ b/src/InterconVis_PedSafety_Enh/cvips_generation.py @@ -12,35 +12,31 @@ def main(): global client, world - parser = argparse.ArgumentParser(description='CARLA 0.9.14 车辆生成工具 (支持环境配置)') - parser.add_argument('--town', type=str, required=True, help='城镇地图 (例如: Town04)') - parser.add_argument('--num_vehicles', type=int, default=10, help='生成车辆数量') + parser = argparse.ArgumentParser(description='CARLA 0.9.14 车辆和行人生成工具 (优化观测版)') + parser.add_argument('--town', type=str, default='Town01', help='城镇地图 (例如: Town01, Town04)') + parser.add_argument('--num_vehicles', type=int, default=20, help='生成车辆数量') + parser.add_argument('--num_pedestrians', type=int, default=100, help='生成行人数量') parser.add_argument('--seed', type=int, default=None, help='随机种子') - # 新增环境参数 parser.add_argument('--weather', type=str, default='clear', choices=['clear', 'rainy', 'cloudy'], help='天气类型') parser.add_argument('--time_of_day', type=str, default='noon', choices=['noon', 'sunset', 'night'], help='时段') args = parser.parse_args() - # 设置随机种子 if args.seed is not None: random.seed(args.seed) print(f"✅ 已设置随机种子: {args.seed}") - # 连接 CARLA client, world = connect_carla_with_retry(args.town) if not world: return - # --- 新增代码:配置天气和时间 --- print("\n🌤️ 正在配置环境...") configure_weather_and_time(world, args.weather, args.time_of_day) - # 生成车辆 print("\n📌 开始生成场景...") generate_vehicles(world, args.num_vehicles) + generate_pedestrians(world, args.num_pedestrians) print("\n✅ 场景生成完毕!") - # 保持运行 print("\n🚗 场景已启动!按 Ctrl+C 退出并清理资源...") try: while True: @@ -49,9 +45,7 @@ def main(): print("\n🛑 收到退出信号,开始清理资源...") # ------------------------------ 辅助函数 ------------------------------ - def connect_carla_with_retry(town_name, max_retries=3, retry_interval=5): - """带重试机制的 CARLA 连接函数""" global client for retry in range(max_retries): try: @@ -72,11 +66,8 @@ def connect_carla_with_retry(town_name, max_retries=3, retry_interval=5): print("💡 请检查:1. CARLA 服务器是否启动 2. 端口是否为 2000") return None, None -# --- 新增函数:配置天气和时间 --- def configure_weather_and_time(world, weather_type, time_of_day): - """配置 CARLA 的天气和时段""" weather = carla.WeatherParameters() - if weather_type == 'clear': weather.cloudiness = 0; weather.precipitation = 0 elif weather_type == 'rainy': @@ -95,7 +86,6 @@ def configure_weather_and_time(world, weather_type, time_of_day): print(f"✅ 已配置环境:天气={weather_type},时段={time_of_day}") def generate_vehicles(world, num_vehicles): - """生成指定数量的车辆并开启自动驾驶 (CARLA 0.9.14 兼容)""" if num_vehicles <= 0: print("ℹ️ 车辆数量为 0,不生成车辆。") return @@ -113,14 +103,11 @@ def generate_vehicles(world, num_vehicles): for i in range(num_vehicles): spawn_point = random.choice(spawn_points) vehicle_bp = random.choice(vehicle_bps) - - # 通过蓝图设置最大速度 (CARLA 0.9.14 兼容方式) try: - max_speed_kmh = random.uniform(25, 35) + max_speed_kmh = random.uniform(20, 30) vehicle_bp.set_attribute('speed', str(max_speed_kmh / 3.6)) except Exception: - pass # 忽略不支持此属性的车辆 - + pass vehicle = world.try_spawn_actor(vehicle_bp, spawn_point) if vehicle: generated_actors.append(vehicle) @@ -129,16 +116,77 @@ def generate_vehicles(world, num_vehicles): num_generated = len([a for a in generated_actors if a.type_id.startswith('vehicle')]) print(f"✅ 成功生成 {num_generated} 辆车辆。") +def generate_pedestrians(world, num_pedestrians): + """生成指定数量的行人并让他们随机行走 (优化观测版)""" + if num_pedestrians <= 0: + print("ℹ️ 行人数量为 0,不生成行人。") + return + + spawn_points = world.get_map().get_spawn_points() + if not spawn_points: + print("⚠️ 未找到任何生成点,无法生成行人。") + return + + pedestrian_bps = world.get_blueprint_library().filter('*walker*') + pedestrian_bps = [bp for bp in pedestrian_bps if bp.id.startswith('walker.pedestrian')] + if not pedestrian_bps: + print("❌ 未找到行人蓝图!请检查 CARLA 资产是否完整。") + return + + controller_bp = world.get_blueprint_library().find('controller.ai.walker') + print(f"👤 正在生成 {num_pedestrians} 个行人... (优化分散度)") + + success_count = 0 + for i in range(num_pedestrians): + retry_count = 5 + while retry_count > 0: + spawn_point = random.choice(spawn_points) + + # --- 核心优化:增加随机偏移,让行人分布更分散 --- + spawn_point.location.x += random.uniform(-8.0, 8.0) + spawn_point.location.y += random.uniform(-8.0, 8.0) + spawn_point.location.z += 0.5 + + try: + pedestrian_bp = random.choice(pedestrian_bps) + pedestrian = world.spawn_actor(pedestrian_bp, spawn_point) + if pedestrian: + generated_actors.append(pedestrian) + controller = world.spawn_actor(controller_bp, carla.Transform(), pedestrian) + generated_actors.append(controller) + + # --- 行为优化 --- + controller.start() + controller.go_to_location(world.get_random_location_from_navigation()) + controller.set_max_speed(random.uniform(0.5, 1.5)) # 更自然的速度范围 + + success_count += 1 + break + except RuntimeError: + retry_count -= 1 + if retry_count == 0: + # 减少失败提示,避免刷屏 + if i % 20 == 0: + print(f"⚠️ 部分行人生成位置被占用,已跳过。") + + if (i + 1) % 25 == 0: + print(f"👤 已生成 {success_count}/{i + 1} 个行人") + + print(f"✅ 成功生成 {success_count} 个行人。") + def clean_up_actors(): - """退出时清理所有生成的 Actor""" global client if generated_actors: print(f"\n🧹 正在清理 {len(generated_actors)} 个仿真对象...") - batch = [carla.command.DestroyActor(x) for x in generated_actors] - if client: - client.apply_batch(batch) - generated_actors.clear() - print("✅ 资源清理完成!") + try: + batch = [carla.command.DestroyActor(x) for x in generated_actors] + if client: + client.apply_batch(batch) + time.sleep(1) + generated_actors.clear() + print("✅ 资源清理完成!") + except Exception as e: + print(f"⚠️ 清理资源时发生错误: {e}") else: print("\n✅ 无需要清理的仿真对象。") From 658433749b94bd6cb963d5fd0a25e39889886d16 Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Wed, 26 Nov 2025 12:24:54 +0800 Subject: [PATCH 24/34] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E6=8C=87=E4=BB=A4?= =?UTF-8?q?=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Terminal_Commands.md | 72 +++++++++++++++---- 1 file changed, 60 insertions(+), 12 deletions(-) diff --git a/src/InterconVis_PedSafety_Enh/Terminal_Commands.md b/src/InterconVis_PedSafety_Enh/Terminal_Commands.md index 58ca64a9ba..548c3bd435 100644 --- a/src/InterconVis_PedSafety_Enh/Terminal_Commands.md +++ b/src/InterconVis_PedSafety_Enh/Terminal_Commands.md @@ -1,24 +1,72 @@ -# 1. 默认配置:在 Town04 生成 10 辆车辆,天气为晴天,时间为中午 +## 命令格式 ```shell -python generate_vehicles_only.py --town Town04 +python cvips_generation.py --town <城镇名称> [--num_vehicles < 数量 >] [--num_pedestrians < 数量 >] [--weather < 天气类型 >] [--time_of_day < 时段 >] [--seed < 种子值 >] ``` -# 2. 自定义车辆数量:在 Town04 生成 15 辆车辆 +## 参数说明 +--town: (必填) CARLA 城镇地图名称 (例如: Town01, Town04)--num_vehicles: (可选) 生成车辆数量,默认值为 20--num_pedestrians:(可选) 生成行人数量,默认值为 100--weather: (可选) 天气类型,可选值: clear (晴天), rainy (雨天), cloudy (多云),默认值为 clear--time_of_day: (可选) 时段,可选值: noon (中午), sunset (日落), night (夜晚),默认值为 noon--seed: (可选) 随机种子,用于复现相同场景 +## 一、基础场景命令 (核心参数覆盖) +### 1. Town01 + 晴天 + 中午 (默认配置) ```shell -python generate_vehicles_only.py --town Town04 --num_vehicles 15 +python cvips_generation.py --town Town01 ``` -# 3. 自定义天气:在 Town04 生成 10 辆车辆,天气为雨天 +### 2. Town01 + 雨天 + 夜晚 ```shell -python generate_vehicles_only.py --town Town04 --weather rainy +python cvips_generation.py --town Town01 --weather rainy --time_of_day night ``` -# 4. 自定义时间:在 Town04 生成 10 辆车辆,时间为夜晚 +### 3. Town04 + 多云 + 日落 ```shell -python generate_vehicles_only.py --town Town04 --time_of_day night +python cvips_generation.py --town Town04 --weather cloudy --time_of_day sunset ``` -# 5. 完整自定义:在 Town07 生成 20 辆车辆,天气为多云,时间为日落 +### 4. Town01 + 晴天 + 夜晚 ```shell -python generate_vehicles_only.py --town Town07 --num_vehicles 20 --weather cloudy --time_of_day sunset +python cvips_generation.py --town Town01 --time_of_day night ``` -# 6. 设置随机种子(保证场景可复现):在 Town10HD 生成 12 辆车辆,使用种子 123 +### 5. Town04 + 雨天 + 中午 ```shell -python generate_vehicles_only.py --town Town10HD --num_vehicles 12 --seed 123 +python cvips_generation.py --town Town04 --weather rainy +``` +## 二、不同密度场景命令 +### 6. Town01 + 低密度 (10 辆车,50 个行人) +```shell +python cvips_generation.py --town Town01 --num_vehicles 10 --num_pedestrians 50 +``` +### 7. Town01 + 中密度 (25 辆车,150 个行人) +```shell +python cvips_generation.py --town Town01 --num_vehicles 25 --num_pedestrians 150 +``` +### 8. Town04 + 高密度 (40 辆车,250 个行人) +```shell +python cvips_generation.py --town Town04 --num_vehicles 40 --num_pedestrians 250 +``` +## 三、随机种子与场景复现命令 + +### 9. Town01 + 种子 123 (可复现) +```shell +python cvips_generation.py --town Town01 --seed 123 +``` +### 10. Town04 + 种子 456 (可复现) +```shell +python cvips_generation.py --town Town04 --seed 456 +``` +### 11. Town01 + 雨天夜晚 + 种子 789 (可复现) +```shell +python cvips_generation.py --town Town01 --weather rainy --time_of_day night --seed 789 +``` +## 四、多参数组合场景命令 +### 12. Town01 + 15 辆车 + 80 个行人 + 雨天 + 日落 + 种子 111 +```shell +python cvips_generation.py --town Town01 --num_vehicles 15 --num_pedestrians 80 --weather rainy --time_of_day sunset --seed 111 +``` +### 13. Town04 + 30 辆车 + 200 个行人 + 多云 + 夜晚 + 种子 222 +```shell +python cvips_generation.py --town Town04 --num_vehicles 30 --num_pedestrians 200 --weather cloudy --time_of_day night --seed 222 +``` +## 五、边缘场景命令 (极限参数) +### 14. Town01 + 极限高密度 (35 辆车,220 个行人) + 雨天 + 夜晚 +```shell +python cvips_generation.py --town Town01 --num_vehicles 35 --num_pedestrians 220 --weather rainy --time_of_day night +``` +### 15. Town04 + 极限低密度 (5 辆车,20 个行人) + 晴天 + 中午 +```shell +python cvips_generation.py --town Town04 --num_vehicles 5 --num_pedestrians 20 --weather clear --time_of_day noon ``` \ No newline at end of file From 8bea41242fac87555633ebf247cbaa29d534bc34 Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Fri, 28 Nov 2025 17:05:38 +0800 Subject: [PATCH 25/34] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E8=AF=B4=E6=98=8E?= =?UTF-8?q?=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/InterconVis_PedSafety_Enh/README.md | 120 +++++++++++------------- 1 file changed, 57 insertions(+), 63 deletions(-) diff --git a/src/InterconVis_PedSafety_Enh/README.md b/src/InterconVis_PedSafety_Enh/README.md index c4cbc54a47..5a534a80a2 100644 --- a/src/InterconVis_PedSafety_Enh/README.md +++ b/src/InterconVis_PedSafety_Enh/README.md @@ -1,85 +1,79 @@ -#CVIPS: 面向提升行人安全的协同视觉 (Connected Vision for Increased Pedestrian Safety) -CVIPS 项目的实现。 -- [X] 数据集 -- [X] CARLA 数据生成代码 - - - -## 数据集 (Dataset) -CVIPS 数据集可在此处获取:[here](https://drive.google.com/drive/folders/1gCCrIslzVkupyF0lj_1I9qXTB2_a4tjd?usp=drive_link). - - - - - -## 安装 (Installation) -请参考 [installation](https://carla.readthedocs.io/en/0.9.14/build_windows) 了解如何在 Windows 上设置 CARLA。 - - +# 项目简介 +CVIPS (Connected Vision for Increased Pedestrian Safety) 是一个致力于通过协同视觉技术(Connected Vision)和 V2X(Vehicle-to-Everything)通信来提升弱势道路使用者(VRU,特别是行人)安全的研究项目。 +在复杂的城市交通场景中,单车智能往往受到视线遮挡(Occlusion)、感知范围受限和恶劣天气的影响。本项目利用 CARLA 仿真器 构建高保真的测试环境,旨在研究: +协同感知 (Collaborative Perception): 融合多视点(车辆、路侧单元 RSU)信息。 +1. 遮挡处理: 解决“鬼探头”等高危场景下的行人检测问题。 +2. 全天候鲁棒性: 在雨天、夜间等极端光照和天气下的感知性能。 +3. 本仓库包含 CVIPS 的核心仿真场景生成工具、数据集采集脚本以及协同感知算法实现。 +# 安装与依赖 (Prerequisites & Installation) +# 系统要求 +- Ubuntu 20.04 / Windows 10+ +- NVIDIA GPU (推荐 8GB+ 显存) +- CARLA Simulator 0.9.14 ## 数据集生成 (Dataset Generation) 我们的数据集是使用 CARLA 模拟器生成的,为协同感知提供了多样化的场景。 -###运行数据生成脚本 (Running the Data Generation Script) - +### carla模拟器构建 +下载以下版本的carla预编译包(可直接运行,无需使用Epic Games Launcher) +- [carla0.9.14](https://github.com/carla-simulator/carla/releases/tag/0.9.14) +### 运行数据生成脚本 (Running the Data Generation Script) 1. 克隆此仓库 - ``` + ```bash git clone https://github.com/cvips/CVIPS.git cd CVIPS ``` - 2. 安装所需的依赖包: - ``` + ```bash pip install -r requirements.txt ``` - 3. 确保 CARLA 已正确安装并运行。在一个单独的终端中启动 CARLA 服务器: - ``` + ```bash /path/to/carla/CarlaUE4.exe ``` - 4. 运行数据生成脚本: - ``` + ```bash python cvips_generation.py ``` - - 该脚本将连接到 CARLA 服务器,并根据指定的参数生成数据集。 -注意:请根据你特定的设置需求,调整 cvips_generation.py 中的 CARLA 服务器路径以及任何配置参数。 -### Sample Examples - -#示例命令 (Sample Examples) - -# 1. 默认配置:在 Town04 生成 10 辆车辆,天气为晴天,时间为中午 -```shell -python generate_vehicles_only.py --town Town04 -``` -# 2. 自定义车辆数量:在 Town04 生成 15 辆车辆 -```shell -python generate_vehicles_only.py --town Town04 --num_vehicles 15 -``` -# 3. 自定义天气:在 Town04 生成 10 辆车辆,天气为雨天 -```shell -python generate_vehicles_only.py --town Town04 --weather rainy -``` -# 4. 自定义时间:在 Town04 生成 10 辆车辆,时间为夜晚 -```shell -python generate_vehicles_only.py --town Town04 --time_of_day night -``` -# 5. 完整自定义:在 Town07 生成 20 辆车辆,天气为多云,时间为日落 -```shell -python generate_vehicles_only.py --town Town07 --num_vehicles 20 --weather cloudy --time_of_day sunset -``` -# 6. 设置随机种子(保证场景可复现):在 Town10HD 生成 12 辆车辆,使用种子 123 -```shell -python generate_vehicles_only.py --town Town10HD --num_vehicles 12 --seed 123 -``` -这些示例展示了城镇、交叉路口类型、天气状况、时间段,车辆和摄像头设置的各种组合。用户可以根据需要修改这些参数以生成不同的场景。 - +注:该脚本将连接到 CARLA 服务器,并根据指定的参数生成数据集,需要单独创建运行脚本。 请根据你特定的设置需求,调整 cvips_generation.py 中的 CARLA 服务器路径以及任何配置参数。 +### 配置虚拟环境 +- CARLA 对 Python 版本(推荐 3.7-3.9)和依赖库版本有严格要求,虚拟环境可避免与其他项目的依赖冲突 +## 示例及格式说明 +- 命令格式 + ```shell + python cvips_generation.py --town <城镇名称> [--num_vehicles < 数量 >] [--num_pedestrians < 数量 >] [--weather < 天气类型 >] [--time_of_day < 时段 >] [--seed < 种子值 >] +## 参数说明 +--town: (必填) CARLA 城镇地图名称 (例如: Town01, Town04)--num_vehicles: (可选) 生成车辆数量,默认值为 20--num_pedestrians:(可选) 生成行人数量,默认值为 100--weather: (可选) 天气类型,可选值: clear (晴天), rainy (雨天), cloudy (多云),默认值为 clear--time_of_day: (可选) 时段,可选值: noon (中午), sunset (日落), night (夜晚),默认值为 noon--seed: (可选) 随机种子,用于复现相同场景 +### 一、基础场景命令 (核心参数覆盖) +1. Town01 + 晴天 + 中午 (默认配置) + ```shell + python cvips_generation.py --town Town01 + ``` +2. Town01 + 雨天 + 夜晚 + ```shell + python cvips_generation.py --town Town01 --weather rainy --time_of_day night + ``` +### 二、不同密度场景命令 +1. Town01 + 低密度 (10 辆车,50 个行人) + ```shell + python cvips_generation.py --town Town01 --num_vehicles 10 --num_pedestrians 50 +2. Town01 + 中密度 (25 辆车,150 个行人) + ```shell + python cvips_generation.py --town Town01 --num_vehicles 25 --num_pedestrians 150 +### 三、随机种子与场景复现命令 + +1. Town01 + 种子 123 (可复现) + ```shell + python cvips_generation.py --town Town01 --seed 123 +2. Town04 + 种子 456 (可复现) + ```shell + python cvips_generation.py --town Town04 --seed 456 +### 四、多参数组合场景命令 +1. Town01 + 15 辆车 + 80 个行人 + 雨天 + 日落 + 种子 111 + ```shell + python cvips_generation.py --town Town01 --num_vehicles 15 --num_pedestrians 80 --weather rainy --time_of_day sunset --seed 111 ### 样本可视化 (Sample Visualizations) 我们提供了可视化结果来展示我们数据集中的不同视角: -![动图加载失败](images/2025-11-24102317-ezgif.com-speed.gif "车辆环境演示1") - - ## 致谢 (Acknowledgement) 本项目基于以下开源项目: BEVerse, Fiery, open-mmlab, 以及 DeepAccident。 From bffe0e45b0fc4d7af925a9266c4f362b9014ba07 Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Fri, 28 Nov 2025 23:50:00 +0800 Subject: [PATCH 26/34] =?UTF-8?q?=E4=BC=98=E5=8C=96=E5=91=BD=E4=BB=A4?= =?UTF-8?q?=E8=AF=B4=E6=98=8E=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/InterconVis_PedSafety_Enh/Terminal_Commands.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/InterconVis_PedSafety_Enh/Terminal_Commands.md b/src/InterconVis_PedSafety_Enh/Terminal_Commands.md index 548c3bd435..d71dbeb60a 100644 --- a/src/InterconVis_PedSafety_Enh/Terminal_Commands.md +++ b/src/InterconVis_PedSafety_Enh/Terminal_Commands.md @@ -3,7 +3,14 @@ python cvips_generation.py --town <城镇名称> [--num_vehicles < 数量 >] [--num_pedestrians < 数量 >] [--weather < 天气类型 >] [--time_of_day < 时段 >] [--seed < 种子值 >] ``` ## 参数说明 ---town: (必填) CARLA 城镇地图名称 (例如: Town01, Town04)--num_vehicles: (可选) 生成车辆数量,默认值为 20--num_pedestrians:(可选) 生成行人数量,默认值为 100--weather: (可选) 天气类型,可选值: clear (晴天), rainy (雨天), cloudy (多云),默认值为 clear--time_of_day: (可选) 时段,可选值: noon (中午), sunset (日落), night (夜晚),默认值为 noon--seed: (可选) 随机种子,用于复现相同场景 +|参数名|类型|默认值|可选值|作用说明| +|:---:|:---:|:---:|:---:|:---:| +|--town|字符串|town01|town01,town04等|指定要加载的CARLA地图| +|--num_vehicles|整数|20|>=0|要生成的自动驾驶车辆数量| +|--num_pedestrians|整数|100|>=0|要生成的自主行走的行人数量| +|--seed|整数|None|任意整数|随机种子,设置后可保证每次运行完全相同的场景,便于复现。| +|--weather|字符串|clear|clear,rainy,cloudy|设置天气,rainy会有明显的降雨和地面反光效果| +|--time_of_day|字符串|noon|noon,sunset,night|设置时间,night会切换到夜晚并开启月光| ## 一、基础场景命令 (核心参数覆盖) ### 1. Town01 + 晴天 + 中午 (默认配置) ```shell From c56df2e3f927b85d99608cba5b1f3f21e96afcab Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Sun, 30 Nov 2025 15:26:23 +0800 Subject: [PATCH 27/34] =?UTF-8?q?=E5=AE=8C=E5=96=84=E8=AF=B4=E6=98=8E?= =?UTF-8?q?=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/InterconVis_PedSafety_Enh/README.md | 38 +++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/src/InterconVis_PedSafety_Enh/README.md b/src/InterconVis_PedSafety_Enh/README.md index 5a534a80a2..885f38496f 100644 --- a/src/InterconVis_PedSafety_Enh/README.md +++ b/src/InterconVis_PedSafety_Enh/README.md @@ -36,12 +36,46 @@ CVIPS (Connected Vision for Increased Pedestrian Safety) 是一个致力于通 注:该脚本将连接到 CARLA 服务器,并根据指定的参数生成数据集,需要单独创建运行脚本。 请根据你特定的设置需求,调整 cvips_generation.py 中的 CARLA 服务器路径以及任何配置参数。 ### 配置虚拟环境 - CARLA 对 Python 版本(推荐 3.7-3.9)和依赖库版本有严格要求,虚拟环境可避免与其他项目的依赖冲突 -## 示例及格式说明 +### 下载Anaconda +- 下载 [Anaconda](https://repo.anaconda.com/archive/Anaconda3-2021.05-Windows-x86_64.exe)。 +- 安装时勾选 “Add Anaconda to PATH”(Windows 需手动勾选,Linux/Mac 默认添加)。 +- 验证安装:打开终端,输入conda --version,显示版本号即成功。 +### 创建激活虚拟环境(仅需执行一次) +1. 打开终端(或 Anaconda Prompt),运行以下命令: + ```bash + # 创建名为cvips_env的虚拟环境(Python3.7适配CARLA 0.9.14) + conda create -n cvips_env python=3.7 + ``` +2. 激活虚拟环境(每次运行脚本前都需执行) + ```bash + conda activate cvips_env # Windows + ``` +### 在虚拟环境中安装 CARLA 依赖(仅需执行一次) +- 激活环境后,直接安装匹配版本的 CARLA Python API: + ```bash + pip install carla==0.9.14 + ``` +### 使用说明 +- 激活虚拟环境(每次运行脚本前都需执行) + ```bash + conda activate cvips_env # Windows + ``` +- 打开 CARLA 0.9.14 模拟器(CarlaUE4.exe/./CarlaUE4.sh)。 +- 进入 cvips 文件夹目录(cd 你的cvips路径) +- 输入想要运行的脚本 +## 使用示例及格式说明 - 命令格式 ```shell python cvips_generation.py --town <城镇名称> [--num_vehicles < 数量 >] [--num_pedestrians < 数量 >] [--weather < 天气类型 >] [--time_of_day < 时段 >] [--seed < 种子值 >] ## 参数说明 ---town: (必填) CARLA 城镇地图名称 (例如: Town01, Town04)--num_vehicles: (可选) 生成车辆数量,默认值为 20--num_pedestrians:(可选) 生成行人数量,默认值为 100--weather: (可选) 天气类型,可选值: clear (晴天), rainy (雨天), cloudy (多云),默认值为 clear--time_of_day: (可选) 时段,可选值: noon (中午), sunset (日落), night (夜晚),默认值为 noon--seed: (可选) 随机种子,用于复现相同场景 +|参数名|类型|默认值|可选值|作用说明| +|:---:|:---:|:---:|:---:|:---:| +|--town|字符串|town01|town01,town04等|指定要加载的CARLA地图| +|--num_vehicles|整数|20|>=0|要生成的自动驾驶车辆数量| +|--num_pedestrians|整数|100|>=0|要生成的自主行走的行人数量| +|--seed|整数|None|任意整数|随机种子,设置后可保证每次运行完全相同的场景,便于复现。| +|--weather|字符串|clear|clear,rainy,cloudy|设置天气,rainy会有明显的降雨和地面反光效果| +|--time_of_day|字符串|noon|noon,sunset,night|设置时间,night会切换到夜晚并开启月光| ### 一、基础场景命令 (核心参数覆盖) 1. Town01 + 晴天 + 中午 (默认配置) ```shell From dc6f4f7066aaff7ac5b120063a94524cb00718a9 Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Sun, 30 Nov 2025 17:16:14 +0800 Subject: [PATCH 28/34] =?UTF-8?q?=E4=BC=98=E5=8C=96=E8=84=9A=E6=9C=AC?= =?UTF-8?q?=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cvips_generation.py | 372 +++++++++--------- 1 file changed, 192 insertions(+), 180 deletions(-) diff --git a/src/InterconVis_PedSafety_Enh/cvips_generation.py b/src/InterconVis_PedSafety_Enh/cvips_generation.py index fdeb2492b2..3b5084034d 100644 --- a/src/InterconVis_PedSafety_Enh/cvips_generation.py +++ b/src/InterconVis_PedSafety_Enh/cvips_generation.py @@ -1,196 +1,208 @@ import carla import argparse import time -import atexit import random +import logging -# 全局变量 -generated_actors = [] -client = None -world = None +# 配置日志 +logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO) def main(): - global client, world - - parser = argparse.ArgumentParser(description='CARLA 0.9.14 车辆和行人生成工具 (优化观测版)') - parser.add_argument('--town', type=str, default='Town01', help='城镇地图 (例如: Town01, Town04)') - parser.add_argument('--num_vehicles', type=int, default=20, help='生成车辆数量') - parser.add_argument('--num_pedestrians', type=int, default=100, help='生成行人数量') - parser.add_argument('--seed', type=int, default=None, help='随机种子') - parser.add_argument('--weather', type=str, default='clear', choices=['clear', 'rainy', 'cloudy'], help='天气类型') - parser.add_argument('--time_of_day', type=str, default='noon', choices=['noon', 'sunset', 'night'], help='时段') - args = parser.parse_args() - - if args.seed is not None: + argparser = argparse.ArgumentParser( + description=__doc__) + argparser.add_argument( + '--town', type=str, default='Town01', help='城镇地图') + argparser.add_argument( + '--num_vehicles', default=30, type=int, help='生成车辆数量') + argparser.add_argument( + '--num_pedestrians', default=50, type=int, help='生成行人数量') + argparser.add_argument( + '--seed', default=None, type=int, help='随机种子') + argparser.add_argument( + '--weather', default='clear', choices=['clear', 'rainy', 'cloudy', 'night'], help='天气预设') + args = argparser.parse_args() + + if args.seed: random.seed(args.seed) - print(f"✅ 已设置随机种子: {args.seed}") - client, world = connect_carla_with_retry(args.town) - if not world: - return + client = carla.Client('localhost', 2000) + client.set_timeout(20.0) - print("\n🌤️ 正在配置环境...") - configure_weather_and_time(world, args.weather, args.time_of_day) + # 全局列表,用于清理 + vehicles_list = [] + walkers_list = [] + all_id = [] - print("\n📌 开始生成场景...") - generate_vehicles(world, args.num_vehicles) - generate_pedestrians(world, args.num_pedestrians) - print("\n✅ 场景生成完毕!") - - print("\n🚗 场景已启动!按 Ctrl+C 退出并清理资源...") try: - while True: - time.sleep(1) - except KeyboardInterrupt: - print("\n🛑 收到退出信号,开始清理资源...") - -# ------------------------------ 辅助函数 ------------------------------ -def connect_carla_with_retry(town_name, max_retries=3, retry_interval=5): - global client - for retry in range(max_retries): - try: - client = carla.Client('localhost', 2000) - client.set_timeout(15.0) - client.load_world(town_name) - world = client.get_world() - print(f"✅ 成功连接 CARLA 并加载地图:{town_name}") - return client, world - except Exception as e: - error_msg = str(e) - if retry < max_retries - 1: - print(f"❌ 连接失败({retry + 1}/{max_retries}):{error_msg}") - print(f"⌛ {retry_interval}秒后重试...") - time.sleep(retry_interval) - else: - print(f"❌ 连接失败(已达最大重试次数):{error_msg}") - print("💡 请检查:1. CARLA 服务器是否启动 2. 端口是否为 2000") - return None, None - -def configure_weather_and_time(world, weather_type, time_of_day): - weather = carla.WeatherParameters() - if weather_type == 'clear': - weather.cloudiness = 0; weather.precipitation = 0 - elif weather_type == 'rainy': - weather.cloudiness = 80; weather.precipitation = 50; weather.precipitation_deposits = 30; weather.wind_intensity = 10; weather.fog_density = 0.3 - elif weather_type == 'cloudy': - weather.cloudiness = 70; weather.precipitation = 0; weather.fog_density = 0.2 - - if time_of_day == 'noon': - weather.sun_altitude_angle = 90; weather.ambient_light = 1.0 - elif time_of_day == 'sunset': - weather.sun_altitude_angle = -15; weather.ambient_light = 0.3 - elif time_of_day == 'night': - weather.sun_altitude_angle = -60; weather.ambient_light = 0.05; weather.moon_altitude_angle = 45; weather.moon_intensity = 0.8 - - world.set_weather(weather) - print(f"✅ 已配置环境:天气={weather_type},时段={time_of_day}") - -def generate_vehicles(world, num_vehicles): - if num_vehicles <= 0: - print("ℹ️ 车辆数量为 0,不生成车辆。") - return - - spawn_points = world.get_map().get_spawn_points() - if not spawn_points: - print("⚠️ 未找到车辆生成点。") - return - - vehicle_bps = world.get_blueprint_library().filter('vehicle.*') - tm = client.get_trafficmanager(8000) - tm.set_global_distance_to_leading_vehicle(2.5) - - print(f"🚗 正在生成 {num_vehicles} 辆车辆...") - for i in range(num_vehicles): - spawn_point = random.choice(spawn_points) - vehicle_bp = random.choice(vehicle_bps) - try: - max_speed_kmh = random.uniform(20, 30) - vehicle_bp.set_attribute('speed', str(max_speed_kmh / 3.6)) - except Exception: - pass - vehicle = world.try_spawn_actor(vehicle_bp, spawn_point) - if vehicle: - generated_actors.append(vehicle) - vehicle.set_autopilot(True, tm.get_port()) - - num_generated = len([a for a in generated_actors if a.type_id.startswith('vehicle')]) - print(f"✅ 成功生成 {num_generated} 辆车辆。") - -def generate_pedestrians(world, num_pedestrians): - """生成指定数量的行人并让他们随机行走 (优化观测版)""" - if num_pedestrians <= 0: - print("ℹ️ 行人数量为 0,不生成行人。") - return - - spawn_points = world.get_map().get_spawn_points() - if not spawn_points: - print("⚠️ 未找到任何生成点,无法生成行人。") - return - - pedestrian_bps = world.get_blueprint_library().filter('*walker*') - pedestrian_bps = [bp for bp in pedestrian_bps if bp.id.startswith('walker.pedestrian')] - if not pedestrian_bps: - print("❌ 未找到行人蓝图!请检查 CARLA 资产是否完整。") - return - - controller_bp = world.get_blueprint_library().find('controller.ai.walker') - print(f"👤 正在生成 {num_pedestrians} 个行人... (优化分散度)") - - success_count = 0 - for i in range(num_pedestrians): - retry_count = 5 - while retry_count > 0: - spawn_point = random.choice(spawn_points) + # 1. 加载地图 + print(f"正在加载地图: {args.town}") + client.load_world(args.town) + world = client.get_world() + + # 2. 设置同步模式 (保证物理计算准确,防止瞬移) + settings = world.get_settings() + settings.synchronous_mode = True + settings.fixed_delta_seconds = 0.05 # 20 FPS + world.apply_settings(settings) + + # 3. 配置交通管理器 + traffic_manager = client.get_trafficmanager(8000) + traffic_manager.set_synchronous_mode(True) + traffic_manager.set_global_distance_to_leading_vehicle(2.5) + traffic_manager.set_hybrid_physics_mode(True) # 远处车辆关闭物理计算 + traffic_manager.set_respawn_dormant_vehicles(True) + + if args.seed: + traffic_manager.set_random_device_seed(args.seed) + + # 4. 设置环境 + configure_weather(world, args.weather) + + # ============================== + # 生成车辆 (Vehicles) + # ============================== + blueprint_library = world.get_blueprint_library() + vehicle_bps = blueprint_library.filter('vehicle.*') + vehicle_bps = [x for x in vehicle_bps if int(x.get_attribute('number_of_wheels')) == 4] + vehicle_bps = [x for x in vehicle_bps if not x.id.endswith('microlino')] + + spawn_points = world.get_map().get_spawn_points() + number_of_spawn_points = len(spawn_points) + + if args.num_vehicles < number_of_spawn_points: + random.shuffle(spawn_points) + elif args.num_vehicles > number_of_spawn_points: + logging.warning(f"请求车辆数 {args.num_vehicles} 超过生成点数量 {number_of_spawn_points}") + args.num_vehicles = number_of_spawn_points + + SpawnActor = carla.command.SpawnActor + SetAutopilot = carla.command.SetAutopilot + FutureActor = carla.command.FutureActor + + batch = [] + for n, transform in enumerate(spawn_points): + if n >= args.num_vehicles: + break + bp = random.choice(vehicle_bps) + if bp.has_attribute('color'): + color = random.choice(bp.get_attribute('color').recommended_values) + bp.set_attribute('color', color) + if bp.has_attribute('driver_id'): + bp.set_attribute('driver_id', random.choice(bp.get_attribute('driver_id').recommended_values)) - # --- 核心优化:增加随机偏移,让行人分布更分散 --- - spawn_point.location.x += random.uniform(-8.0, 8.0) - spawn_point.location.y += random.uniform(-8.0, 8.0) - spawn_point.location.z += 0.5 + bp.set_attribute('role_name', 'autopilot') + + batch.append(SpawnActor(bp, transform) + .then(SetAutopilot(FutureActor, True, traffic_manager.get_port()))) + + for response in client.apply_batch_sync(batch, True): + if response.error: + logging.error(response.error) + else: + vehicles_list.append(response.actor_id) + + print(f"✅ 已生成 {len(vehicles_list)} 辆车") + + for actor in world.get_actors(vehicles_list): + traffic_manager.vehicle_percentage_speed_difference(actor, random.randint(-10, 10)) + traffic_manager.ignore_lights_percentage(actor, 0) + traffic_manager.ignore_signs_percentage(actor, 0) + traffic_manager.auto_lane_change(actor, True) + + # ============================== + # 生成行人 (Pedestrians) + # ============================== + spawn_points = [] + for i in range(args.num_pedestrians): + spawn_point = carla.Transform() + loc = world.get_random_location_from_navigation() + if (loc != None): + spawn_point.location = loc + spawn_points.append(spawn_point) + + walker_bp_list = blueprint_library.filter('walker.pedestrian.*') + walker_controller_bp = blueprint_library.find('controller.ai.walker') + + batch = [] + for spawn_point in spawn_points: + walker_bp = random.choice(walker_bp_list) + if walker_bp.has_attribute('is_invincible'): + walker_bp.set_attribute('is_invincible', 'false') + batch.append(SpawnActor(walker_bp, spawn_point)) + + results = client.apply_batch_sync(batch, True) + for i in range(len(results)): + if results[i].error: + logging.error(results[i].error) + else: + walkers_list.append({"id": results[i].actor_id}) + + batch = [] + walker_controller_list = [] + for i in range(len(walkers_list)): + batch.append(SpawnActor(walker_controller_bp, carla.Transform(), walkers_list[i]["id"])) + + results = client.apply_batch_sync(batch, True) + for i in range(len(results)): + if results[i].error: + logging.error(results[i].error) + else: + walkers_list[i]["con"] = results[i].actor_id + walker_controller_list.append(results[i].actor_id) + + all_id = vehicles_list + [x['id'] for x in walkers_list] + [x['con'] for x in walkers_list if 'con' in x] + print(f"✅ 已生成 {len(walkers_list)} 个行人") + + world.tick() + world.set_pedestrians_cross_factor(0.1) + + for i, controller_id in enumerate(walker_controller_list): + controller = world.get_actor(controller_id) + controller.start() + controller.go_to_location(world.get_random_location_from_navigation()) - try: - pedestrian_bp = random.choice(pedestrian_bps) - pedestrian = world.spawn_actor(pedestrian_bp, spawn_point) - if pedestrian: - generated_actors.append(pedestrian) - controller = world.spawn_actor(controller_bp, carla.Transform(), pedestrian) - generated_actors.append(controller) - - # --- 行为优化 --- - controller.start() - controller.go_to_location(world.get_random_location_from_navigation()) - controller.set_max_speed(random.uniform(0.5, 1.5)) # 更自然的速度范围 - - success_count += 1 - break - except RuntimeError: - retry_count -= 1 - if retry_count == 0: - # 减少失败提示,避免刷屏 - if i % 20 == 0: - print(f"⚠️ 部分行人生成位置被占用,已跳过。") + # ============ 修改点开始 ============ + # 设置更自然的速度: 0.5 ~ 1.3 m/s (约 1.8 ~ 4.7 km/h) + # 之前的 1.0~1.8 太快了 + speed = random.uniform(0.5, 1.3) + controller.set_max_speed(speed) + # ============ 修改点结束 ============ + + print("\n🚀 仿真已启动!按 Ctrl+C 停止...") - if (i + 1) % 25 == 0: - print(f"👤 已生成 {success_count}/{i + 1} 个行人") - - print(f"✅ 成功生成 {success_count} 个行人。") - -def clean_up_actors(): - global client - if generated_actors: - print(f"\n🧹 正在清理 {len(generated_actors)} 个仿真对象...") - try: - batch = [carla.command.DestroyActor(x) for x in generated_actors] - if client: - client.apply_batch(batch) - time.sleep(1) - generated_actors.clear() - print("✅ 资源清理完成!") - except Exception as e: - print(f"⚠️ 清理资源时发生错误: {e}") - else: - print("\n✅ 无需要清理的仿真对象。") - -atexit.register(clean_up_actors) - -if __name__ == "__main__": + while True: + world.tick() + + except KeyboardInterrupt: + print("\n🛑 正在停止仿真...") + finally: + print(f"🧹 清理 {len(all_id)} 个仿真对象...") + for i, controller_id in enumerate(walker_controller_list): + try: + controller = world.get_actor(controller_id) + controller.stop() + except: + pass + client.apply_batch([carla.command.DestroyActor(x) for x in all_id]) + + if world: + settings = world.get_settings() + settings.synchronous_mode = False + settings.fixed_delta_seconds = None + world.apply_settings(settings) + + print("✅ 清理完成,程序退出。") + +def configure_weather(world, weather_type): + weather_presets = { + 'clear': carla.WeatherParameters.ClearNoon, + 'cloudy': carla.WeatherParameters.CloudyNoon, + 'rainy': carla.WeatherParameters.HardRainNoon, + 'night': carla.WeatherParameters.ClearNight + } + preset = weather_presets.get(weather_type, carla.WeatherParameters.ClearNoon) + world.set_weather(preset) + print(f"🌤️ 天气设置为: {weather_type}") + +if __name__ == '__main__': main() \ No newline at end of file From 7954d2ad45a636c1619872b7c689785179d20276 Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Mon, 8 Dec 2025 10:27:58 +0800 Subject: [PATCH 29/34] =?UTF-8?q?=E7=94=9F=E6=88=90=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=92=8C=E8=BD=A6=E8=BE=86=E8=84=9A=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cvips_collector.py | 193 ++++++++++++++++++ 1 file changed, 193 insertions(+) create mode 100644 src/InterconVis_PedSafety_Enh/cvips_collector.py diff --git a/src/InterconVis_PedSafety_Enh/cvips_collector.py b/src/InterconVis_PedSafety_Enh/cvips_collector.py new file mode 100644 index 0000000000..92f5b0f378 --- /dev/null +++ b/src/InterconVis_PedSafety_Enh/cvips_collector.py @@ -0,0 +1,193 @@ +import carla +import random +import queue +import os +import argparse +import time + +# ================= 配置区域 ================= +OUTPUT_FOLDER = "_out_cvips_data" + +# 【重要】改成 True 开启保存。建议先跑一次 False 确认画面正常 +ENABLE_SAVING = True + +# 每隔几帧保存一次?(建议 10-20,太小会卡,太大错过细节) +SAVE_INTERVAL = 10 +# =========================================== + +def main(): + argparser = argparse.ArgumentParser(description="CVIPS 数据采集脚本 V4") + argparser.add_argument('--town', default='Town01', help='地图名称') + argparser.add_argument('--num_vehicles', default=20, type=int, help='背景车辆数') + argparser.add_argument('--num_walkers', default=30, type=int, help='行人数') + args = argparser.parse_args() + + # 创建目录 + if ENABLE_SAVING: + os.makedirs(f"{OUTPUT_FOLDER}/ego_rgb", exist_ok=True) + os.makedirs(f"{OUTPUT_FOLDER}/rsu_rgb", exist_ok=True) + print(f"📁 图片将保存在: {os.path.abspath(OUTPUT_FOLDER)}") + + client = carla.Client('localhost', 2000) + client.set_timeout(60.0) + + print(f"正在加载地图 {args.town} (可能需要几秒)...") + world = client.load_world(args.town) + + # 设置同步模式 + settings = world.get_settings() + settings.synchronous_mode = True + settings.fixed_delta_seconds = 0.05 + world.apply_settings(settings) + + traffic_manager = client.get_trafficmanager(8000) + traffic_manager.set_synchronous_mode(True) + + # 这里的队列用于接收传感器数据 + sensor_queue = queue.Queue() + actor_list = [] + + try: + # --- 1. 生成环境 --- + print("正在构建场景...") + blueprint_library = world.get_blueprint_library() + spawn_points = world.get_map().get_spawn_points() + + ego_spawn_point = spawn_points[0] + npc_spawn_points = spawn_points[1:] + + # 生成背景车辆 + bg_vehicle_bp = blueprint_library.filter('vehicle.*')[0] + for _ in range(args.num_vehicles): + t = random.choice(npc_spawn_points) + actor = world.try_spawn_actor(bg_vehicle_bp, t) + if actor: + actor.set_autopilot(True) + actor_list.append(actor) + + # 生成行人 + walker_bp = blueprint_library.filter('walker.pedestrian.*')[0] + for _ in range(args.num_walkers): + loc = world.get_random_location_from_navigation() + if loc: + w = world.try_spawn_actor(walker_bp, carla.Transform(loc)) + if w: actor_list.append(w) + + # --- 2. 主车 (Ego) --- + print("生成主车...") + ego_bp = blueprint_library.find('vehicle.tesla.model3') + ego_bp.set_attribute('role_name', 'hero') + ego_vehicle = world.spawn_actor(ego_bp, ego_spawn_point) + ego_vehicle.set_autopilot(True) + actor_list.append(ego_vehicle) + + # --- 3. RSU (路侧单元) --- + rsu_loc = ego_spawn_point.location + rsu_loc.z += 8.0 + rsu_loc.x += 5.0 + # 俯视 45 度 + rsu_transform = carla.Transform(rsu_loc, carla.Rotation(pitch=-45, yaw=ego_spawn_point.rotation.yaw)) + + # --- 4. 传感器设置 (关键修改) --- + camera_bp = blueprint_library.find('sensor.camera.rgb') + camera_bp.set_attribute('image_size_x', '800') + camera_bp.set_attribute('image_size_y', '600') + camera_bp.set_attribute('fov', '90') # 视野广一点 + + # 【关键修改:微调主车相机位置】 + # 之前的 x=1.5, z=2.4 可能在某些车型的车顶里。 + # 改为 x=1.0 (靠后一点), z=2.0 (低一点),通常在挡风玻璃内侧。 + cam_transform = carla.Transform(carla.Location(x=1.0, z=2.0)) + ego_cam = world.spawn_actor(camera_bp, cam_transform, attach_to=ego_vehicle) + actor_list.append(ego_cam) + + rsu_cam = world.spawn_actor(camera_bp, rsu_transform) + actor_list.append(rsu_cam) + + # 监听数据 + ego_cam.listen(lambda image: sensor_queue.put((image.frame, 'ego_rgb', image))) + rsu_cam.listen(lambda image: sensor_queue.put((image.frame, 'rsu_rgb', image))) + + print("\n🔥 正在预热仿真 (Warm Up) ... 等待 50 帧让画面稳定") + # --- 5. 热身阶段 (不保存数据) --- + for _ in range(50): + world.tick() + # 把产生的垃圾数据从队列里清空 + try: + for _ in range(2): sensor_queue.get(timeout=1.0) + except: pass + + print("🚀 仿真正式开始!正在采集数据...") + + # --- 6. 正式循环 --- + frame_number = 0 + spectator = world.get_spectator() + + while True: + # 1. 推动世界一帧 + world.tick() + w_frame = world.get_snapshot().frame + + # 2. 视角跟随 (保持 V3 的跟随逻辑) + ego_tf = ego_vehicle.get_transform() + ego_fv = ego_tf.get_forward_vector() + spectator_loc = ego_tf.location - (ego_fv * 6.0) + carla.Location(z=3.0) + spectator_rot = ego_tf.rotation + spectator_rot.pitch = -15.0 + spectator.set_transform(carla.Transform(spectator_loc, spectator_rot)) + + # 3. 严格的数据获取逻辑 + # 我们需要确保取出的 2 张图,确实属于当前的这一帧 w_frame + try: + current_frame_data = {} # 用字典存:{'ego_rgb': img, 'rsu_rgb': img} + + # 尝试从队列取数据,直到把这一帧的两个相机都取到 + # 设置超时防止死循环 + timeout_counter = 0 + while len(current_frame_data) < 2 and timeout_counter < 10: + data = sensor_queue.get(timeout=1.0) + frame_id, s_type, img_obj = data + + # 只有当数据帧号 == 世界帧号,才算有效数据 + # (允许有 1 帧的误差,因为CARLA有时候会差1帧) + if abs(frame_id - w_frame) <= 1: + current_frame_data[s_type] = img_obj + else: + # 丢弃旧数据 + pass + timeout_counter += 1 + + # 4. 保存数据 + if ENABLE_SAVING and (frame_number % SAVE_INTERVAL == 0): + # 确保两个相机的数据都齐了才保存 + if len(current_frame_data) == 2: + print(f"💾 保存帧 [{w_frame}] | Ego & RSU OK", end='\r') + + # 保存 Ego + fname_ego = f"{OUTPUT_FOLDER}/ego_rgb/{w_frame:06d}.png" + current_frame_data['ego_rgb'].save_to_disk(fname_ego) + + # 保存 RSU + fname_rsu = f"{OUTPUT_FOLDER}/rsu_rgb/{w_frame:06d}.png" + current_frame_data['rsu_rgb'].save_to_disk(fname_rsu) + else: + print(f"⚠️ 丢帧: 数据不完整", end='\r') + + except queue.Empty: + print("⚠️ 传感器数据超时") + continue + + frame_number += 1 + + except KeyboardInterrupt: + print("\n🛑 用户停止") + finally: + print("\n🧹 清理现场...") + settings.synchronous_mode = False + world.apply_settings(settings) + for actor in actor_list: + if actor.is_alive: actor.destroy() + print("✅ 完成。") + +if __name__ == '__main__': + main() \ No newline at end of file From be38ad9504226c2e018d593fceb2d59efb179b88 Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Mon, 8 Dec 2025 11:26:56 +0800 Subject: [PATCH 30/34] =?UTF-8?q?=E4=BC=98=E5=8C=96=E8=84=9A=E6=9C=AC?= =?UTF-8?q?=E6=96=87=E4=BB=B6=EF=BC=8C=E5=87=8F=E5=B0=91=E7=94=BB=E9=9D=A2?= =?UTF-8?q?=E5=8D=A1=E9=A1=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cvips_collector.py | 211 +++++++++++------- 1 file changed, 129 insertions(+), 82 deletions(-) diff --git a/src/InterconVis_PedSafety_Enh/cvips_collector.py b/src/InterconVis_PedSafety_Enh/cvips_collector.py index 92f5b0f378..6e3372d150 100644 --- a/src/InterconVis_PedSafety_Enh/cvips_collector.py +++ b/src/InterconVis_PedSafety_Enh/cvips_collector.py @@ -4,55 +4,77 @@ import os import argparse import time +import threading # ================= 配置区域 ================= -OUTPUT_FOLDER = "_out_cvips_data" +# 输出文件夹名称 +OUTPUT_FOLDER = "_out_cvips_final" -# 【重要】改成 True 开启保存。建议先跑一次 False 确认画面正常 +# 是否开启保存 (调试视角时可设为 False) ENABLE_SAVING = True -# 每隔几帧保存一次?(建议 10-20,太小会卡,太大错过细节) -SAVE_INTERVAL = 10 +# 采集间隔:每 15 帧保存一次 (平衡 1080P 的存储压力) +SAVE_INTERVAL = 15 # =========================================== +# 全局标志位,控制后台线程何时停止 +writing_thread_running = True + def main(): - argparser = argparse.ArgumentParser(description="CVIPS 数据采集脚本 V4") + argparser = argparse.ArgumentParser(description="CVIPS 最终版数据采集脚本") argparser.add_argument('--town', default='Town01', help='地图名称') - argparser.add_argument('--num_vehicles', default=20, type=int, help='背景车辆数') - argparser.add_argument('--num_walkers', default=30, type=int, help='行人数') + argparser.add_argument('--num_vehicles', default=25, type=int, help='背景车辆数') + argparser.add_argument('--num_walkers', default=40, type=int, help='行人数') args = argparser.parse_args() - # 创建目录 + # 1. 创建保存目录 if ENABLE_SAVING: os.makedirs(f"{OUTPUT_FOLDER}/ego_rgb", exist_ok=True) os.makedirs(f"{OUTPUT_FOLDER}/rsu_rgb", exist_ok=True) - print(f"📁 图片将保存在: {os.path.abspath(OUTPUT_FOLDER)}") - - client = carla.Client('localhost', 2000) - client.set_timeout(60.0) - - print(f"正在加载地图 {args.town} (可能需要几秒)...") - world = client.load_world(args.town) - - # 设置同步模式 + print(f"📁 数据保存路径: {os.path.abspath(OUTPUT_FOLDER)}") + + # 2. 连接 CARLA (使用 127.0.0.1 避免 Windows 防火墙问题) + try: + client = carla.Client('127.0.0.1', 2000) + client.set_timeout(60.0) + print(f"正在加载地图 {args.town} ...") + world = client.load_world(args.town) + except RuntimeError as e: + print(f"❌ 连接失败: {e}") + print("请确保 CARLA 模拟器已启动!") + return + + # 3. 设置高画质天气 (正午晴天) + world.set_weather(carla.WeatherParameters.ClearNoon) + + # 4. 设置同步模式 settings = world.get_settings() settings.synchronous_mode = True - settings.fixed_delta_seconds = 0.05 + settings.fixed_delta_seconds = 0.05 # 固定 20 FPS world.apply_settings(settings) traffic_manager = client.get_trafficmanager(8000) traffic_manager.set_synchronous_mode(True) - # 这里的队列用于接收传感器数据 - sensor_queue = queue.Queue() + # 5. 初始化队列和列表 + sensor_queue = queue.Queue() # 接收原始数据 + save_queue = queue.Queue() # 后台保存队列 actor_list = [] + # 6. 启动后台保存线程 + global writing_thread_running + writing_thread_running = True + save_thread = threading.Thread(target=save_worker, args=(save_queue,)) + save_thread.start() + print("✅ 后台保存服务已启动") + try: - # --- 1. 生成环境 --- - print("正在构建场景...") + # --- 生成环境 --- + print("正在构建交通场景...") blueprint_library = world.get_blueprint_library() spawn_points = world.get_map().get_spawn_points() + # 分离主车点和NPC点,防止碰撞 ego_spawn_point = spawn_points[0] npc_spawn_points = spawn_points[1:] @@ -73,7 +95,7 @@ def main(): w = world.try_spawn_actor(walker_bp, carla.Transform(loc)) if w: actor_list.append(w) - # --- 2. 主车 (Ego) --- + # --- 生成主车 (Ego) --- print("生成主车...") ego_bp = blueprint_library.find('vehicle.tesla.model3') ego_bp.set_attribute('role_name', 'hero') @@ -81,23 +103,24 @@ def main(): ego_vehicle.set_autopilot(True) actor_list.append(ego_vehicle) - # --- 3. RSU (路侧单元) --- + # --- 生成 RSU (路侧单元) --- rsu_loc = ego_spawn_point.location - rsu_loc.z += 8.0 + rsu_loc.z += 12.0 # 12米高空 rsu_loc.x += 5.0 - # 俯视 45 度 - rsu_transform = carla.Transform(rsu_loc, carla.Rotation(pitch=-45, yaw=ego_spawn_point.rotation.yaw)) + rsu_transform = carla.Transform(rsu_loc, carla.Rotation(pitch=-70, yaw=ego_spawn_point.rotation.yaw)) - # --- 4. 传感器设置 (关键修改) --- + # --- 传感器设置 (1080P 高画质) --- camera_bp = blueprint_library.find('sensor.camera.rgb') - camera_bp.set_attribute('image_size_x', '800') - camera_bp.set_attribute('image_size_y', '600') - camera_bp.set_attribute('fov', '90') # 视野广一点 - - # 【关键修改:微调主车相机位置】 - # 之前的 x=1.5, z=2.4 可能在某些车型的车顶里。 - # 改为 x=1.0 (靠后一点), z=2.0 (低一点),通常在挡风玻璃内侧。 - cam_transform = carla.Transform(carla.Location(x=1.0, z=2.0)) + camera_bp.set_attribute('image_size_x', '1920') + camera_bp.set_attribute('image_size_y', '1080') + camera_bp.set_attribute('fov', '90') + # 优化画质属性 + camera_bp.set_attribute('exposure_mode', 'histogram') + camera_bp.set_attribute('motion_blur_intensity', '0.2') + + # 主车相机:第三人称 (车后6米,高3米),防遮挡 + cam_transform = carla.Transform(carla.Location(x=-6.0, z=3.0), carla.Rotation(pitch=-20)) + ego_cam = world.spawn_actor(camera_bp, cam_transform, attach_to=ego_vehicle) actor_list.append(ego_cam) @@ -108,86 +131,110 @@ def main(): ego_cam.listen(lambda image: sensor_queue.put((image.frame, 'ego_rgb', image))) rsu_cam.listen(lambda image: sensor_queue.put((image.frame, 'rsu_rgb', image))) - print("\n🔥 正在预热仿真 (Warm Up) ... 等待 50 帧让画面稳定") - # --- 5. 热身阶段 (不保存数据) --- + print("\n🔥 正在预热 (Warm Up)... 请保持 CARLA 窗口在前台!") for _ in range(50): world.tick() - # 把产生的垃圾数据从队列里清空 try: + # 清空预热期的垃圾数据 for _ in range(2): sensor_queue.get(timeout=1.0) except: pass - print("🚀 仿真正式开始!正在采集数据...") + print("🚀 采集开始!按 Ctrl+C 优雅退出...") - # --- 6. 正式循环 --- frame_number = 0 spectator = world.get_spectator() while True: - # 1. 推动世界一帧 + # 1. 物理计算一帧 world.tick() w_frame = world.get_snapshot().frame - # 2. 视角跟随 (保持 V3 的跟随逻辑) - ego_tf = ego_vehicle.get_transform() - ego_fv = ego_tf.get_forward_vector() - spectator_loc = ego_tf.location - (ego_fv * 6.0) + carla.Location(z=3.0) - spectator_rot = ego_tf.rotation - spectator_rot.pitch = -15.0 - spectator.set_transform(carla.Transform(spectator_loc, spectator_rot)) - - # 3. 严格的数据获取逻辑 - # 我们需要确保取出的 2 张图,确实属于当前的这一帧 w_frame + # 2. 移动观众视角跟随主车 (方便你观察) + spectator.set_transform(ego_cam.get_transform()) + try: - current_frame_data = {} # 用字典存:{'ego_rgb': img, 'rsu_rgb': img} - - # 尝试从队列取数据,直到把这一帧的两个相机都取到 - # 设置超时防止死循环 + # 3. 获取数据 + current_frame_data = {} timeout_counter = 0 + # 尝试凑齐两个相机的数据 while len(current_frame_data) < 2 and timeout_counter < 10: data = sensor_queue.get(timeout=1.0) frame_id, s_type, img_obj = data - - # 只有当数据帧号 == 世界帧号,才算有效数据 - # (允许有 1 帧的误差,因为CARLA有时候会差1帧) + # 允许 1 帧的误差 if abs(frame_id - w_frame) <= 1: current_frame_data[s_type] = img_obj - else: - # 丢弃旧数据 - pass timeout_counter += 1 - # 4. 保存数据 + # 4. 放入后台队列 if ENABLE_SAVING and (frame_number % SAVE_INTERVAL == 0): - # 确保两个相机的数据都齐了才保存 if len(current_frame_data) == 2: - print(f"💾 保存帧 [{w_frame}] | Ego & RSU OK", end='\r') + print(f"Frame: {w_frame} | 待存队列: {save_queue.qsize()}", end='\r') + save_queue.put(current_frame_data) - # 保存 Ego - fname_ego = f"{OUTPUT_FOLDER}/ego_rgb/{w_frame:06d}.png" - current_frame_data['ego_rgb'].save_to_disk(fname_ego) - - # 保存 RSU - fname_rsu = f"{OUTPUT_FOLDER}/rsu_rgb/{w_frame:06d}.png" - current_frame_data['rsu_rgb'].save_to_disk(fname_rsu) - else: - print(f"⚠️ 丢帧: 数据不完整", end='\r') - except queue.Empty: - print("⚠️ 传感器数据超时") continue frame_number += 1 except KeyboardInterrupt: - print("\n🛑 用户停止") + print("\n🛑 用户请求停止") + finally: - print("\n🧹 清理现场...") - settings.synchronous_mode = False - world.apply_settings(settings) + print("\n🧹 正在执行清理程序...") + + # 1. 停止后台线程 + writing_thread_running = False + + # 2. 等待剩余照片保存完毕 (解决报错的关键) + if not save_queue.empty(): + print(f"⏳ 正在保存剩余的 {save_queue.qsize()} 张照片,请不要关闭窗口...", end='', flush=True) + save_thread.join() + print(" 保存完毕!") + else: + save_thread.join() + + # 3. 恢复 CARLA 设置 (防止下次启动变卡) + try: + if world: + settings = world.get_settings() + settings.synchronous_mode = False + settings.fixed_delta_seconds = None + world.apply_settings(settings) + except: + pass + + # 4. 安全销毁所有对象 + print("🗑️ 销毁车辆和传感器...") for actor in actor_list: - if actor.is_alive: actor.destroy() - print("✅ 完成。") + try: + if actor.is_alive: + actor.destroy() + except: + pass # 忽略销毁时的错误 + + print("✅ 全部完成,程序安全退出。") + +# --- 后台工作线程 --- +def save_worker(q): + while writing_thread_running or not q.empty(): + try: + data_dict = q.get(timeout=1.0) + ego_img = data_dict['ego_rgb'] + rsu_img = data_dict['rsu_rgb'] + + # 保存 Ego + path_ego = f"{OUTPUT_FOLDER}/ego_rgb/{ego_img.frame:06d}.png" + ego_img.save_to_disk(path_ego) + + # 保存 RSU + path_rsu = f"{OUTPUT_FOLDER}/rsu_rgb/{rsu_img.frame:06d}.png" + rsu_img.save_to_disk(path_rsu) + + q.task_done() + except queue.Empty: + continue + except Exception as e: + print(f"保存错误: {e}") if __name__ == '__main__': main() \ No newline at end of file From 50f765e34d9b352b7891d9bb75a9516b83dba774 Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Mon, 8 Dec 2025 11:35:12 +0800 Subject: [PATCH 31/34] =?UTF-8?q?=E4=BC=98=E5=8C=96=E8=84=9A=E6=9C=AC?= =?UTF-8?q?=E6=96=87=E4=BB=B6=EF=BC=8C=E5=87=8F=E5=B0=91=E7=94=BB=E9=9D=A2?= =?UTF-8?q?=E5=8D=A1=E9=A1=BF=EF=BC=9B=E6=9B=B4=E6=96=B0README.md=EF=BC=9B?= =?UTF-8?q?=E5=88=A0=E9=99=A4Terminal=5FCommands.txt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/InterconVis_PedSafety_Enh/README.md | 1 + src/InterconVis_PedSafety_Enh/Terminal_Commands.txt | 11 ----------- 2 files changed, 1 insertion(+), 11 deletions(-) delete mode 100644 src/InterconVis_PedSafety_Enh/Terminal_Commands.txt diff --git a/src/InterconVis_PedSafety_Enh/README.md b/src/InterconVis_PedSafety_Enh/README.md index 885f38496f..d8b2452482 100644 --- a/src/InterconVis_PedSafety_Enh/README.md +++ b/src/InterconVis_PedSafety_Enh/README.md @@ -108,6 +108,7 @@ CVIPS (Connected Vision for Increased Pedestrian Safety) 是一个致力于通 我们提供了可视化结果来展示我们数据集中的不同视角: + ## 致谢 (Acknowledgement) 本项目基于以下开源项目: BEVerse, Fiery, open-mmlab, 以及 DeepAccident。 diff --git a/src/InterconVis_PedSafety_Enh/Terminal_Commands.txt b/src/InterconVis_PedSafety_Enh/Terminal_Commands.txt deleted file mode 100644 index 56726ea4aa..0000000000 --- a/src/InterconVis_PedSafety_Enh/Terminal_Commands.txt +++ /dev/null @@ -1,11 +0,0 @@ -# 测试1:基础场景(Town04+4岔路口+晴天+中午) -python cvips_generation.py --town Town04 --intersection 4way --weather clear --time_of_day noon - -# 测试2:复杂场景(Town10HD+3岔路口+雨天+日落+高行人密度) -python cvips_generation.py --town Town10HD --intersection 3way --weather rainy --time_of_day sunset --crowd_level high --crossing_percentage 0.3 - -# 测试3:夜间场景(Town07+4岔路口+阴天+夜间+自定义随机种子) -python cvips_generation.py --town Town07 --intersection 4way --weather cloudy --time_of_day night --seed_value 123 --scenario scenario00005 - -# 测试4:最简场景(Town04+3岔路口+晴天+日落) -python cvips_generation.py --town Town04 --intersection 3way --weather clear --time_of_day sunset \ No newline at end of file From 3d6ed720b4213d48646fb7af381890022555876b Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Mon, 15 Dec 2025 10:33:30 +0800 Subject: [PATCH 32/34] =?UTF-8?q?=E6=9B=B4=E6=96=B0README.md=E6=96=87?= =?UTF-8?q?=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/InterconVis_PedSafety_Enh/README.md | 35 ++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/src/InterconVis_PedSafety_Enh/README.md b/src/InterconVis_PedSafety_Enh/README.md index d8b2452482..518d07a8f2 100644 --- a/src/InterconVis_PedSafety_Enh/README.md +++ b/src/InterconVis_PedSafety_Enh/README.md @@ -104,9 +104,42 @@ CVIPS (Connected Vision for Increased Pedestrian Safety) 是一个致力于通 1. Town01 + 15 辆车 + 80 个行人 + 雨天 + 日落 + 种子 111 ```shell python cvips_generation.py --town Town01 --num_vehicles 15 --num_pedestrians 80 --weather rainy --time_of_day sunset --seed 111 +## 数据集生成 +数据集由cvip_collector.py生成,保存在out_cvips_v9(主文件夹) +- 📂 ego_rgb/ : 存放主车(Tesla)视角的图片(命名格式为 帧号.png)。 +- 📂 rsu_rgb/ : 存放路侧单元(RSU,安装在高处)视角的图片。 +### 运行命令 +### 基础模式 (默认参数) +- 在Town01地图,生成25辆车和40个行人,晴朗中午。 + ```shell + python cvips_collector.py + ``` +### 更换地图 (例如 Town02, Town10HD) +使用 --town 参数。 +- 在 Town02 采集 + ```shell + python cvips_collector.py --town Town02 + ``` +- 在 Town10HD (高清地图) 采集 + ```shell + python cvips_collector.py --town Town10HD + ``` +### 调整交通密度 (拥堵/空旷) +使用 --num_vehicles 和 --num_walkers。 +- 拥堵场景 (50辆车, 80人): + ```shell + python cvips_collector.py --num_vehicles 50 --num_walkers 80 + ``` +- 空旷场景 (5辆车, 0人): + ```shell + python cvips_collector.py --num_vehicles 5 --num_walkers 0 + ``` ### 样本可视化 (Sample Visualizations) - 我们提供了可视化结果来展示我们数据集中的不同视角: +- 车辆自动行驶(视角为车后) +- +- 模拟环境 +- ## 致谢 (Acknowledgement) From 7f1b657ed2540fd6ad8ce4a194340ff628c2a69c Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Wed, 17 Dec 2025 17:50:21 +0800 Subject: [PATCH 33/34] =?UTF-8?q?=E4=BC=98=E5=8C=96=E8=84=9A=E6=9C=AC?= =?UTF-8?q?=E6=96=87=E4=BB=B6=EF=BC=8C=E5=A2=9E=E6=B7=BB=E5=85=B6=E4=BB=96?= =?UTF-8?q?=E5=85=83=E7=B4=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cvips_collector.py | 340 +++++++++--------- 1 file changed, 180 insertions(+), 160 deletions(-) diff --git a/src/InterconVis_PedSafety_Enh/cvips_collector.py b/src/InterconVis_PedSafety_Enh/cvips_collector.py index 6e3372d150..ae0398fec3 100644 --- a/src/InterconVis_PedSafety_Enh/cvips_collector.py +++ b/src/InterconVis_PedSafety_Enh/cvips_collector.py @@ -5,236 +5,256 @@ import argparse import time import threading +import logging +import sys # ================= 配置区域 ================= -# 输出文件夹名称 -OUTPUT_FOLDER = "_out_cvips_final" - -# 是否开启保存 (调试视角时可设为 False) -ENABLE_SAVING = True - -# 采集间隔:每 15 帧保存一次 (平衡 1080P 的存储压力) -SAVE_INTERVAL = 15 +OUTPUT_FOLDER = "_out_dataset_v10" +ENABLE_SAVING = True +SAVE_INTERVAL = 10 # 每 10 帧存一次 +TARGET_FPS = 30 +FIXED_DELTA_SECONDS = 1.0 / TARGET_FPS # =========================================== -# 全局标志位,控制后台线程何时停止 +# 全局控制标志 writing_thread_running = True + +def configure_weather(world, weather_type, time_of_day): + """设置天气和光照""" + weather_presets = { + 'clear': carla.WeatherParameters.ClearNoon, + 'cloudy': carla.WeatherParameters.CloudyNoon, + 'rainy': carla.WeatherParameters.HardRainNoon, + 'wet': carla.WeatherParameters.WetNoon, + } + weather = weather_presets.get(weather_type, carla.WeatherParameters.ClearNoon) + + if time_of_day == 'day': + weather.sun_altitude_angle = 75.0 + elif time_of_day == 'sunset': + weather.sun_altitude_angle = 10.0 + elif time_of_day == 'night': + weather.sun_altitude_angle = -90.0 + + world.set_weather(weather) + + +def cleanup_previous_hero(world): + """启动前清理可能残留的主车""" + actors = world.get_actors() + potential_heroes = [x for x in actors if + x.type_id.startswith('vehicle') and x.attributes.get('role_name') == 'hero'] + if potential_heroes: + print(f"🧹 发现 {len(potential_heroes)} 辆残留的主车,正在清理...") + for h in potential_heroes: + h.destroy() + + def main(): - argparser = argparse.ArgumentParser(description="CVIPS 最终版数据采集脚本") + argparser = argparse.ArgumentParser(description="CVIPS Pro - 强制退出版") argparser.add_argument('--town', default='Town01', help='地图名称') - argparser.add_argument('--num_vehicles', default=25, type=int, help='背景车辆数') + argparser.add_argument('--num_vehicles', default=40, type=int, help='车辆数') argparser.add_argument('--num_walkers', default=40, type=int, help='行人数') + argparser.add_argument('--weather', default='clear', choices=['clear', 'rainy', 'cloudy', 'wet'], help='天气') + argparser.add_argument('--time_of_day', default='day', choices=['day', 'sunset', 'night'], help='时间') + argparser.add_argument('--max_frames', default=1000, type=int, help='采集多少帧后自动停止(0为不停止)') + args = argparser.parse_args() - # 1. 创建保存目录 + scene_name = f"{args.town}_{args.weather}_{args.time_of_day}" + scene_output_path = os.path.join(OUTPUT_FOLDER, scene_name) + if ENABLE_SAVING: - os.makedirs(f"{OUTPUT_FOLDER}/ego_rgb", exist_ok=True) - os.makedirs(f"{OUTPUT_FOLDER}/rsu_rgb", exist_ok=True) - print(f"📁 数据保存路径: {os.path.abspath(OUTPUT_FOLDER)}") + os.makedirs(f"{scene_output_path}/ego_rgb", exist_ok=True) + os.makedirs(f"{scene_output_path}/rsu_rgb", exist_ok=True) - # 2. 连接 CARLA (使用 127.0.0.1 避免 Windows 防火墙问题) - try: - client = carla.Client('127.0.0.1', 2000) - client.set_timeout(60.0) - print(f"正在加载地图 {args.town} ...") - world = client.load_world(args.town) - except RuntimeError as e: - print(f"❌ 连接失败: {e}") - print("请确保 CARLA 模拟器已启动!") - return - - # 3. 设置高画质天气 (正午晴天) - world.set_weather(carla.WeatherParameters.ClearNoon) - - # 4. 设置同步模式 - settings = world.get_settings() - settings.synchronous_mode = True - settings.fixed_delta_seconds = 0.05 # 固定 20 FPS - world.apply_settings(settings) - - traffic_manager = client.get_trafficmanager(8000) - traffic_manager.set_synchronous_mode(True) - - # 5. 初始化队列和列表 - sensor_queue = queue.Queue() # 接收原始数据 - save_queue = queue.Queue() # 后台保存队列 - actor_list = [] - - # 6. 启动后台保存线程 + client = None + world = None + actor_list = [] + + sensor_queue = queue.Queue() + save_queue = queue.Queue() global writing_thread_running - writing_thread_running = True - save_thread = threading.Thread(target=save_worker, args=(save_queue,)) - save_thread.start() - print("✅ 后台保存服务已启动") try: - # --- 生成环境 --- - print("正在构建交通场景...") + client = carla.Client('127.0.0.1', 2000) + client.set_timeout(10.0) + + world = client.get_world() + if world.get_map().name.split('/')[-1] != args.town: + print(f"🗺️ 正在切换地图至 {args.town} ...") + world = client.load_world(args.town) + else: + print(f"🗺️ 当前已是 {args.town},准备就绪。") + + cleanup_previous_hero(world) + configure_weather(world, args.weather, args.time_of_day) + + settings = world.get_settings() + settings.synchronous_mode = True + settings.fixed_delta_seconds = FIXED_DELTA_SECONDS + world.apply_settings(settings) + + traffic_manager = client.get_trafficmanager(8000) + traffic_manager.set_synchronous_mode(True) + traffic_manager.set_global_distance_to_leading_vehicle(2.5) + + writing_thread_running = True + save_thread = threading.Thread(target=save_worker, args=(save_queue, scene_output_path)) + # 【修改1】设置为守护线程,主程序一死它必须死 + save_thread.daemon = True + save_thread.start() + + # --- 生成 Actor --- + print("🚗 生成交通流...") blueprint_library = world.get_blueprint_library() spawn_points = world.get_map().get_spawn_points() + random.shuffle(spawn_points) - # 分离主车点和NPC点,防止碰撞 ego_spawn_point = spawn_points[0] npc_spawn_points = spawn_points[1:] - # 生成背景车辆 - bg_vehicle_bp = blueprint_library.filter('vehicle.*')[0] - for _ in range(args.num_vehicles): - t = random.choice(npc_spawn_points) - actor = world.try_spawn_actor(bg_vehicle_bp, t) - if actor: - actor.set_autopilot(True) - actor_list.append(actor) - - # 生成行人 + bg_vehicle_bp = blueprint_library.filter('vehicle.*') + bg_vehicle_bp = [x for x in bg_vehicle_bp if int(x.get_attribute('number_of_wheels')) == 4] + + batch = [] + for n, transform in enumerate(npc_spawn_points): + if n >= args.num_vehicles: break + bp = random.choice(bg_vehicle_bp) + if bp.has_attribute('color'): + bp.set_attribute('color', random.choice(bp.get_attribute('color').recommended_values)) + batch.append(carla.command.SpawnActor(bp, transform).then( + carla.command.SetAutopilot(carla.command.FutureActor, True, traffic_manager.get_port()))) + + for response in client.apply_batch_sync(batch, True): + if not response.error: actor_list.append(response.actor_id) + walker_bp = blueprint_library.filter('walker.pedestrian.*')[0] for _ in range(args.num_walkers): loc = world.get_random_location_from_navigation() if loc: w = world.try_spawn_actor(walker_bp, carla.Transform(loc)) - if w: actor_list.append(w) + if w: actor_list.append(w.id) - # --- 生成主车 (Ego) --- - print("生成主车...") + print("🚘 生成主车...") ego_bp = blueprint_library.find('vehicle.tesla.model3') ego_bp.set_attribute('role_name', 'hero') ego_vehicle = world.spawn_actor(ego_bp, ego_spawn_point) ego_vehicle.set_autopilot(True) - actor_list.append(ego_vehicle) + actor_list.append(ego_vehicle.id) - # --- 生成 RSU (路侧单元) --- rsu_loc = ego_spawn_point.location - rsu_loc.z += 12.0 # 12米高空 - rsu_loc.x += 5.0 - rsu_transform = carla.Transform(rsu_loc, carla.Rotation(pitch=-70, yaw=ego_spawn_point.rotation.yaw)) + rsu_loc.z += 10.0 + rsu_loc.x += 8.0 + rsu_transform = carla.Transform(rsu_loc, carla.Rotation(pitch=-60, yaw=ego_spawn_point.rotation.yaw)) + cam_transform = carla.Transform(carla.Location(x=-1.5, z=2.4), carla.Rotation(pitch=-15)) - # --- 传感器设置 (1080P 高画质) --- camera_bp = blueprint_library.find('sensor.camera.rgb') camera_bp.set_attribute('image_size_x', '1920') camera_bp.set_attribute('image_size_y', '1080') - camera_bp.set_attribute('fov', '90') - # 优化画质属性 - camera_bp.set_attribute('exposure_mode', 'histogram') - camera_bp.set_attribute('motion_blur_intensity', '0.2') - - # 主车相机:第三人称 (车后6米,高3米),防遮挡 - cam_transform = carla.Transform(carla.Location(x=-6.0, z=3.0), carla.Rotation(pitch=-20)) - + camera_bp.set_attribute('sensor_tick', str(FIXED_DELTA_SECONDS)) + ego_cam = world.spawn_actor(camera_bp, cam_transform, attach_to=ego_vehicle) - actor_list.append(ego_cam) - rsu_cam = world.spawn_actor(camera_bp, rsu_transform) - actor_list.append(rsu_cam) + actor_list.append(ego_cam.id) + actor_list.append(rsu_cam.id) - # 监听数据 ego_cam.listen(lambda image: sensor_queue.put((image.frame, 'ego_rgb', image))) rsu_cam.listen(lambda image: sensor_queue.put((image.frame, 'rsu_rgb', image))) - print("\n🔥 正在预热 (Warm Up)... 请保持 CARLA 窗口在前台!") - for _ in range(50): - world.tick() - try: - # 清空预热期的垃圾数据 - for _ in range(2): sensor_queue.get(timeout=1.0) - except: pass + print(f"\n🚀 采集开始! 按 Ctrl+C 停止") - print("🚀 采集开始!按 Ctrl+C 优雅退出...") - frame_number = 0 - spectator = world.get_spectator() + spectator = world.get_spectator() + clock = pygame_clock() while True: - # 1. 物理计算一帧 world.tick() w_frame = world.get_snapshot().frame - - # 2. 移动观众视角跟随主车 (方便你观察) + fps = clock.tick() spectator.set_transform(ego_cam.get_transform()) + if args.max_frames > 0 and frame_number >= args.max_frames: + print("\n✅ 已达到目标帧数,自动停止。") + break + try: - # 3. 获取数据 current_frame_data = {} - timeout_counter = 0 - # 尝试凑齐两个相机的数据 - while len(current_frame_data) < 2 and timeout_counter < 10: + timeout = 0 + while len(current_frame_data) < 2 and timeout < 10: data = sensor_queue.get(timeout=1.0) - frame_id, s_type, img_obj = data - # 允许 1 帧的误差 - if abs(frame_id - w_frame) <= 1: - current_frame_data[s_type] = img_obj - timeout_counter += 1 + fid, stype, img = data + if abs(fid - w_frame) <= 2: + current_frame_data[stype] = img + timeout += 1 - # 4. 放入后台队列 if ENABLE_SAVING and (frame_number % SAVE_INTERVAL == 0): if len(current_frame_data) == 2: - print(f"Frame: {w_frame} | 待存队列: {save_queue.qsize()}", end='\r') + print(f"FPS: {fps:.1f} | Frame: {frame_number} | 队列: {save_queue.qsize()} ", end='\r') save_queue.put(current_frame_data) - except queue.Empty: - continue - + pass frame_number += 1 except KeyboardInterrupt: - print("\n🛑 用户请求停止") - + print("\n\n🛑 用户中断") + except Exception as e: + print(f"\n❌ 错误: {e}") finally: - print("\n🧹 正在执行清理程序...") - - # 1. 停止后台线程 + print("\n♻️ 正在退出...") + + # 停止写入 writing_thread_running = False - - # 2. 等待剩余照片保存完毕 (解决报错的关键) - if not save_queue.empty(): - print(f"⏳ 正在保存剩余的 {save_queue.qsize()} 张照片,请不要关闭窗口...", end='', flush=True) - save_thread.join() - print(" 保存完毕!") - else: - save_thread.join() + if 'save_thread' in locals() and save_thread.is_alive(): + print("⏳ 等待后台写入完成...", end='') + save_thread.join(timeout=5) # 最多等5秒,不等了 + print("Done") - # 3. 恢复 CARLA 设置 (防止下次启动变卡) - try: - if world: - settings = world.get_settings() - settings.synchronous_mode = False - settings.fixed_delta_seconds = None - world.apply_settings(settings) - except: - pass + # 销毁对象 + if client and actor_list: + client.apply_batch([carla.command.DestroyActor(x) for x in actor_list]) - # 4. 安全销毁所有对象 - print("🗑️ 销毁车辆和传感器...") - for actor in actor_list: - try: - if actor.is_alive: - actor.destroy() - except: - pass # 忽略销毁时的错误 - - print("✅ 全部完成,程序安全退出。") - -# --- 后台工作线程 --- -def save_worker(q): + # 恢复异步 + if world: + settings = world.get_settings() + settings.synchronous_mode = False + settings.fixed_delta_seconds = None + world.apply_settings(settings) + + print("✅ 资源已释放,强制返回终端。") + # 【修改2】核弹级退出:直接调用系统底层退出,不给 Python 挂起的机会 + os._exit(0) + + +class pygame_clock: + def __init__(self): + self.start_time = time.time() + self.frame_count = 0 + self.fps = 0 + + def tick(self): + self.frame_count += 1 + elapsed = time.time() - self.start_time + if elapsed > 1.0: + self.fps = self.frame_count / elapsed + self.start_time = time.time() + self.frame_count = 0 + return self.fps + + +def save_worker(q, path): while writing_thread_running or not q.empty(): try: - data_dict = q.get(timeout=1.0) - ego_img = data_dict['ego_rgb'] - rsu_img = data_dict['rsu_rgb'] - - # 保存 Ego - path_ego = f"{OUTPUT_FOLDER}/ego_rgb/{ego_img.frame:06d}.png" - ego_img.save_to_disk(path_ego) - - # 保存 RSU - path_rsu = f"{OUTPUT_FOLDER}/rsu_rgb/{rsu_img.frame:06d}.png" - rsu_img.save_to_disk(path_rsu) - + data = q.get(timeout=0.1) + ego = data['ego_rgb'] + rsu = data['rsu_rgb'] + ego.save_to_disk(f"{path}/ego_rgb/{ego.frame:08d}.jpg") + rsu.save_to_disk(f"{path}/rsu_rgb/{rsu.frame:08d}.jpg") q.task_done() - except queue.Empty: - continue - except Exception as e: - print(f"保存错误: {e}") + except: + pass + if __name__ == '__main__': main() \ No newline at end of file From fabe0285017ece409341e8ddfdfbcbf5e1b3c125 Mon Sep 17 00:00:00 2001 From: haoliuaa <2121765139@qq.com> Date: Wed, 17 Dec 2025 18:25:53 +0800 Subject: [PATCH 34/34] =?UTF-8?q?=E8=A1=A5=E5=85=85=E5=AD=A6=E6=A0=A1?= =?UTF-8?q?=E4=BB=93=E5=BA=93=E6=A0=B9=E7=9B=AE=E5=BD=95=E7=BC=BA=E5=A4=B1?= =?UTF-8?q?=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ requirements.txt | 5 +++++ 2 files changed, 53 insertions(+) create mode 100644 README.md create mode 100644 requirements.txt diff --git a/README.md b/README.md new file mode 100644 index 0000000000..c198e51470 --- /dev/null +++ b/README.md @@ -0,0 +1,48 @@ +# 神经网络实现代理 + +利用神经网络/ROS 实现 Carla(车辆、行人的感知、规划、控制)、AirSim、Mujoco 中人和载具的代理。 + +## 环境配置 + +* 平台:Windows 10/11,Ubuntu 20.04/22.04 +* 软件:Python 3.7-3.12(需支持3.7)、Pytorch(尽量不使用Tensorflow) +* 相关软件下载 [链接](https://pan.baidu.com/s/1IFhCd8X9lI24oeYQm5-Edw?pwd=hutb) + + +## 贡献指南 + +准备提交代码之前,请阅读 [贡献指南](https://github.com/OpenHUTB/.github/blob/master/CONTRIBUTING.md) 。 +代码的优化包括:注释、[PEP 8 风格调整](https://peps.pythonlang.cn/pep-0008/) 、将神经网络应用到Carla模拟器中、撰写对应 [文档](https://openhutb.github.io/nn/) 、添加 [源代码对应的自动化测试](https://docs.github.com/zh/actions/use-cases-and-examples/building-and-testing/building-and-testing-python) 等(从Carla场景中获取神经网络所需数据或将神经网络的结果输出到场景中)。 + +### 约定 + +* 每个模块位于`src/{模块名}`目录下,`模块名`需要用2-3个单词表示,首字母不需要大写,下划线`_`分隔,不能宽泛,越具体越好 +* 每个模块的入口须为`main.`开头,比如:main.py、main.cpp、main.bat、main.sh等,提供的ROS功能以`main.launch`文件作为启动配置文件 +* 每次pull request都需要保证能够通过main脚本直接运行整个模块,在提交信息中提供运行动图或截图;Pull Request的标题不能随意,需要概括具体的修改内容;README.md文档中提供运行环境和运行步骤的说明 +* 仓库尽量保存文本文件,二进制文件需要慎重,如运行需要示例数据,可以保存少量数据,大量数据可以通过提供网盘链接并说明下载链接和运行说明 + + +### 文档生成 + +测试生成的文档: +1. 安装python 3.11,并使用以下命令安装`mkdocs`和相关依赖: +```shell +pip install mkdocs -i http://mirrors.aliyun.com/pypi/simple --trusted-host mirrors.aliyun.com +pip install -r requirements.txt +``` +(可选)安装完成后使用`mkdocs --version`查看是否安装成功。 + +2. 在命令行中进入`nn`目录下,运行: +```shell +mkdocs build +mkdocs serve +``` +然后使用浏览器打开 [http://127.0.0.1:8000](http://127.0.0.1:8000),查看文档页面能否正常显示。 + +## 参考 + +* [代理模拟器文档](https://openhutb.github.io) +* 已有相关 [无人车](https://openhutb.github.io/doc/used_by/) 、[无人机](https://openhutb.github.io/air_doc/third/used_by/) 、[具身人](https://openhutb.github.io/doc/pedestrian/humanoid/) 的实现 +* [神经网络原理](https://github.com/OpenHUTB/neuro) + + diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000..2d3d95d455 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +python-markdown-math +imageio +numpy +matplotlib +tensorflow \ No newline at end of file