From 425a84d99ff10089779e5046917c118834bb58d9 Mon Sep 17 00:00:00 2001 From: ou-yang220 <2101542906@qq.com> Date: Sat, 20 Dec 2025 22:27:07 +0800 Subject: [PATCH 1/2] =?UTF-8?q?fix:=20V2X=E8=B7=AF=E4=BE=A7=E6=84=9F?= =?UTF-8?q?=E7=9F=A5=E4=BF=AE=E5=A4=8Ddraw=5Fboxes=E5=8F=82=E6=95=B0+?= =?UTF-8?q?=E5=8A=A8=E6=80=81=E7=94=BB=E9=9D=A2=E9=9D=99=E6=AD=A2=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../v2xEdgeYolov7Light2.py | 151 ++++++++++++++++++ 1 file changed, 151 insertions(+) create mode 100644 src/V2X_edge_intelligence/src/road_side_perception/v2xEdgeYolov7Light2.py diff --git a/src/V2X_edge_intelligence/src/road_side_perception/v2xEdgeYolov7Light2.py b/src/V2X_edge_intelligence/src/road_side_perception/v2xEdgeYolov7Light2.py new file mode 100644 index 0000000000..044b2a6dd7 --- /dev/null +++ b/src/V2X_edge_intelligence/src/road_side_perception/v2xEdgeYolov7Light2.py @@ -0,0 +1,151 @@ +# git commit -m "V2X路侧感知系统(动态画面版+参数修复)" +# 修复:draw_boxes参数缺失 + 动态画面静止问题 +# ============================================== +import sys +import os +import time +import cv2 +import numpy as np + + +# 1. 强制加载Carla + +CARLA_EGG_PATH = r"D:\WindowsNoEditor\PythonAPI\carla\dist\carla-0.9.10-py3.7-win-amd64.egg" +if not os.path.exists(CARLA_EGG_PATH): + print(f"❌ Carla egg文件不存在!路径:{CARLA_EGG_PATH}") + sys.exit(1) +sys.path.insert(0, CARLA_EGG_PATH) +try: + import carla + print("✅ Carla模块加载成功!") +except Exception as e: + print(f"❌ Carla导入失败:{e}") + sys.exit(1) + + +# 2. 核心功能函数(修复参数传递) +# -------------------------- +def init_carla_camera(): + """初始化Carla摄像头(开启同步模式,修复画面静止)""" + try: + client = carla.Client('localhost', 2000) + client.set_timeout(20.0) + world = client.get_world() + + # 解除Carla服务端暂停,开启同步模式 + world_settings = world.get_settings() + world_settings.synchronous_mode = True + world_settings.fixed_delta_seconds = 0.05 + world.apply_settings(world_settings) + print("✅ Carla仿真模式已开启(同步模式+20fps)") + + # 创建摄像头蓝图(关闭缓存) + bp_lib = world.get_blueprint_library() + camera_bp = bp_lib.find('sensor.camera.rgb') + camera_bp.set_attribute('image_size_x', '640') + camera_bp.set_attribute('image_size_y', '480') + camera_bp.set_attribute('fov', '90') + camera_bp.set_attribute('sensor_tick', '0.0') # 无延迟 + + # 摄像头位置 + spawn_point = carla.Transform( + carla.Location(x=10.0, y=0.0, z=5.0), + carla.Rotation(pitch=-10.0, yaw=0.0, roll=0.0) + ) + + # 生成摄像头Actor + camera = world.spawn_actor(camera_bp, spawn_point) + image_data = {'image': None, 'new_frame': False} + + # 回调函数:仅接收最新帧 + def camera_callback(image): + array = np.frombuffer(image.raw_data, dtype=np.uint8) + array = np.reshape(array, (480, 640, 4))[:, :, :3][:, :, ::-1] + image_data['image'] = array + image_data['new_frame'] = True + + camera.listen(camera_callback) + print("✅ Carla摄像头初始化成功!画面将实时刷新") + return client, world, camera, image_data + except Exception as e: + print(f"❌ Carla摄像头初始化失败:{e}") + print("⚠️ 请确保:1. CarlaUE4.exe已启动 2. 地图加载完成") + return None, None, None, None + +def simulate_detection(image): + """模拟检测框(随画面动态刷新)""" + h, w = image.shape[:2] + t = time.time() % 10 + offset_x = int(np.sin(t) * 10) + offset_y = int(np.cos(t) * 5) + boxes = [ + [w//4 + offset_x, h//4 + offset_y, w//3 + offset_x, h//3 + offset_y], + [w//2 - offset_x, h//2 - offset_y, w//1.5 - offset_x, h//1.5 - offset_y], + ] + return np.array(boxes) + +def draw_boxes(image, boxes): + """绘制动态检测框(参数完整:image + boxes)""" + for box in boxes: + x1, y1, x2, y2 = map(int, box) + x1 = max(0, min(x1, 639)) + y1 = max(0, min(y1, 479)) + x2 = max(0, min(x2, 639)) + y2 = max(0, min(y2, 479)) + cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2) + cv2.putText(image, "Real-time Carla View (20fps)", (10, 30), + cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2) + return image + +# -------------------------- +# 3. 主程序(修复draw_boxes参数传递) +# -------------------------- +def main(): + print("===== V2X路侧感知系统(动态画面版)=====") + + # 初始化Carla + client, world, camera, image_data = init_carla_camera() + if camera is None: + return + + # 主循环(同步仿真帧) + print("✅ 系统启动成功!按 'q' 键退出 | 可在CarlaUE4.exe中移动视角") + try: + while True: + # 触发Carla仿真步,生成新帧 + world.tick() + time.sleep(0.01) + + # 处理新帧(核心修复:传递完整参数) + if image_data['new_frame'] and image_data['image'] is not None: + frame = image_data['image'].copy() + image_data['new_frame'] = False + + # 1. 生成检测框 + boxes = simulate_detection(frame) + # 2. 绘制检测框(修复:传递frame + boxes两个参数) + frame = draw_boxes(frame, boxes) + + # 显示动态画面 + cv2.imshow("V2X Road-Side Perception (Dynamic View)", frame) + + # 按q退出 + if cv2.waitKey(1) & 0xFF == ord('q'): + break + except KeyboardInterrupt: + print("\n⚠️ 用户手动中断程序") + finally: + # 恢复Carla默认设置 + if world: + world_settings = world.get_settings() + world_settings.synchronous_mode = False + world.apply_settings(world_settings) + # 清理资源 + if camera: + camera.stop() + camera.destroy() + cv2.destroyAllWindows() + print("✅ 系统已退出,Carla设置已恢复默认!") + +if __name__ == "__main__": + main() \ No newline at end of file From 883d052a8c71262be0576fcd99913bc69f3a84b8 Mon Sep 17 00:00:00 2001 From: ou-yang220 <2101542906@qq.com> Date: Sun, 21 Dec 2025 12:50:05 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E8=B7=AF=E4=BE=A7=E6=84=9F=E7=9F=A5?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E9=9B=86=E9=A2=84=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/V2X_edge_intelligence/src/README.md | 12 ++++ src/V2X_edge_intelligence/src/main.py | 92 +++++++++++++++++++++++++ 2 files changed, 104 insertions(+) create mode 100644 src/V2X_edge_intelligence/src/README.md create mode 100644 src/V2X_edge_intelligence/src/main.py diff --git a/src/V2X_edge_intelligence/src/README.md b/src/V2X_edge_intelligence/src/README.md new file mode 100644 index 0000000000..1778860e16 --- /dev/null +++ b/src/V2X_edge_intelligence/src/README.md @@ -0,0 +1,12 @@ +# 路侧感知数据集预处理模块(Carla适配) +## 模块说明 +本模块针对Carla模拟器生成的车路协同路侧感知数据,实现轻量化预处理(数据生成、增强、划分),全程无第三方依赖,直接运行出结果。 + +## 运行环境 +- Python 3.6+(无需任何第三方库,仅用内置模块) +- 操作系统:Windows/Linux/macOS均可 + +## 运行步骤 +1. 进入模块目录: + ```bash + cd C:\Users\21015\PycharmProjects\nn2\V2X_edge_intelligence\src \ No newline at end of file diff --git a/src/V2X_edge_intelligence/src/main.py b/src/V2X_edge_intelligence/src/main.py new file mode 100644 index 0000000000..8143a8ec03 --- /dev/null +++ b/src/V2X_edge_intelligence/src/main.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +路侧感知数据集预处理(Carla适配) +零第三方依赖(仅Python内置库),完全无报错! +运行方式:python main.py +""" +import json +import os +import random + + +# ===================== 第一步:生成模拟Carla数据(纯文本,不用图片) ===================== +def generate_demo_data(): + """生成模拟Carla标注数据(纯文本,无需图片/OpenCV,零报错)""" + os.makedirs("demo_carla_data", exist_ok=True) + # 生成Carla场景标注(纯JSON文本,模拟感知数据) + anno_data = { + "carla_scenes": [ + {"scene_id": 1001, "frame_id": 0, + "obstacles": [{"type": "car", "bbox": [100, 100, 200, 200], "distance": 8.5}]}, + {"scene_id": 1002, "frame_id": 1, + "obstacles": [{"type": "person", "bbox": [150, 150, 250, 250], "distance": 5.2}]} + ] + } + with open("demo_carla_data/carla_anno.json", "w", encoding="utf-8") as f: + json.dump(anno_data, f, indent=2) + print("✅ 模拟Carla标注数据生成完成 → demo_carla_data/carla_anno.json") + + +# ===================== 第二步:数据增强(文本层面模拟,无需图片) ===================== +def simple_augment(): + """模拟数据增强(文本层面扩充,比如添加噪声、复制数据)""" + with open("demo_carla_data/carla_anno.json", "r", encoding="utf-8") as f: + data = json.load(f) + + # 模拟增强:为每个场景添加随机噪声(模拟图像增强) + augmented_data = [] + for scene in data["carla_scenes"]: + # 复制场景并添加噪声 + aug_scene = scene.copy() + aug_scene["aug_type"] = "random_brightness" # 模拟亮度增强 + # 给障碍物距离加随机噪声 + for obs in aug_scene["obstacles"]: + obs["distance"] = round(obs["distance"] + random.uniform(-0.5, 0.5), 2) + augmented_data.append(aug_scene) + + # 保存增强后数据 + with open("demo_carla_data/carla_anno_augmented.json", "w", encoding="utf-8") as f: + json.dump({"carla_scenes_augmented": augmented_data}, f, indent=2) + print("✅ 数据增强完成 → demo_carla_data/carla_anno_augmented.json") + + +# ===================== 第三步:数据集划分(纯文本,内置库实现) ===================== +def split_dataset(): + """划分数据集(8:1:1,纯文本处理)""" + with open("demo_carla_data/carla_anno.json", "r", encoding="utf-8") as f: + data = json.load(f) + + scenes = data["carla_scenes"] + random.shuffle(scenes) # 随机打乱 + total = len(scenes) + train_size = int(total * 0.8) + val_size = int((total - train_size) / 2) + + # 划分数据 + train_data = scenes[:train_size] + val_data = scenes[train_size:train_size + val_size] + test_data = scenes[train_size + val_size:] + + # 保存划分结果 + split_result = { + "train_scenes": train_data, + "val_scenes": val_data, + "test_scenes": test_data, + "split_ratio": "train:80% | val:10% | test:10%" + } + with open("demo_carla_data/carla_split_result.json", "w", encoding="utf-8") as f: + json.dump(split_result, f, indent=2) + print("✅ 数据集划分完成 → demo_carla_data/carla_split_result.json") + print(f" 划分结果:训练集{len(train_data)}条 | 验证集{len(val_data)}条 | 测试集{len(test_data)}条") + + +# ===================== 主函数:一键运行 ===================== +if __name__ == "__main__": + print("===== 路侧感知数据集预处理(Carla适配) =====\n") + generate_demo_data() + simple_augment() + split_dataset() + print("\n🎉 所有步骤运行完成!生成文件列表:") + for file in os.listdir("demo_carla_data"): + print(f" - demo_carla_data/{file}") \ No newline at end of file