Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 52 additions & 1 deletion src/Yolov3_Autonomous_Vehicle_Object_Detection/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,44 @@
import queue
import numpy as np
import carla
import argparse # [新增] 引入命令行参数解析库

from config import config
from utils.carla_client import CarlaClient
from models.yolo_detector import YOLODetector
<<<<<<< HEAD
=======
# [新增] 引入新的绘图函数
>>>>>>> af1df56e41e216690d1e8e26081896cfd8849632
from utils.visualization import draw_results, draw_safe_zone
from utils.planner import SimplePlanner
from utils.logger import PerformanceLogger


# [新增] 参数解析函数
def parse_arguments():
parser = argparse.ArgumentParser(description="Autonomous Vehicle Object Detection System")

parser.add_argument("--host", default=config.CARLA_HOST, help="CARLA Host IP")
parser.add_argument("--port", type=int, default=config.CARLA_PORT, help="CARLA Port")
parser.add_argument("--no-render", action="store_true", help="Disable OpenCV rendering window (Headless mode)")

return parser.parse_args()


def main():
<<<<<<< HEAD
# 1. 解析命令行参数
args = parse_arguments()

=======
# 1. 初始化模块
>>>>>>> af1df56e41e216690d1e8e26081896cfd8849632
print("[Main] 初始化模块...")
# 打印运行模式
if args.no_render:
print("[INFO] 运行模式: Headless (无窗口渲染)")

detector = YOLODetector(
cfg_path=config.YOLO_CONFIG_PATH,
weights_path=config.YOLO_WEIGHTS_PATH,
Expand All @@ -27,7 +52,13 @@ def main():

planner = SimplePlanner()
logger = PerformanceLogger(log_dir=config.LOG_DIR)
<<<<<<< HEAD

# [Mod] 使用命令行参数初始化客户端
client = CarlaClient(host=args.host, port=args.port)
=======
client = CarlaClient()
>>>>>>> af1df56e41e216690d1e8e26081896cfd8849632

if not client.connect():
return
Expand Down Expand Up @@ -62,6 +93,23 @@ def main():
# --- 记录数据 ---
fps = 1 / (time.time() - start_time)
logger.log_step(fps, len(results))
<<<<<<< HEAD

# --- 可视化 (根据 --no-render 参数决定是否显示) ---
if not args.no_render:
frame = draw_safe_zone(frame)
frame = draw_results(frame, results, detector.classes)

cv2.putText(frame, f"FPS: {fps:.2f}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
if is_brake:
cv2.putText(frame, "EMERGENCY BRAKING!", (150, 300), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, 0, 255),
4)
cv2.putText(frame, warning_msg, (180, 350), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)

cv2.imshow("CARLA Object Detection", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
=======

# --- 可视化 ---
# 1. 先画安全走廊 (蓝色辅助线)
Expand All @@ -80,6 +128,7 @@ def main():

if cv2.waitKey(1) & 0xFF == ord('q'):
break
>>>>>>> af1df56e41e216690d1e8e26081896cfd8849632

except queue.Empty:
continue
Expand All @@ -91,7 +140,9 @@ def main():
print("[Main] 正在清理资源...")
client.destroy_actors()
logger.close()
cv2.destroyAllWindows()
# 只有创建了窗口才需要销毁
if not args.no_render:
cv2.destroyAllWindows()
print("[Main] 程序已退出")


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ class CarlaClient:
CARLA 模拟器客户端封装类
"""

def __init__(self):
self.host = config.CARLA_HOST
self.port = config.CARLA_PORT
# [Mod] 修改 __init__ 方法,允许覆盖 host 和 port
def __init__(self, host=None, port=None):
# 如果传入了参数就用传入的,否则用 config 里的默认值
self.host = host if host else config.CARLA_HOST
self.port = port if port else config.CARLA_PORT
self.timeout = config.CARLA_TIMEOUT

self.client = None
Expand Down Expand Up @@ -50,7 +52,6 @@ def spawn_vehicle(self):
print("[ERROR] 世界未加载,请先连接!")
return None

# [Refactor] 使用配置文件中的车型
model_name = config.VEHICLE_MODEL
bp = self.blueprint_library.find(model_name)

Expand All @@ -74,7 +75,6 @@ def setup_camera(self):
camera_bp.set_attribute('image_size_y', str(config.CAMERA_HEIGHT))
camera_bp.set_attribute('fov', str(config.CAMERA_FOV))

# [Refactor] 使用配置文件中的安装位置
spawn_point = carla.Transform(carla.Location(x=config.CAMERA_POS_X, z=config.CAMERA_POS_Z))

self.camera = self.world.spawn_actor(camera_bp, spawn_point, attach_to=self.vehicle)
Expand Down