From 0c2bca80545a3f92ea7ca6967d89825c53027c25 Mon Sep 17 00:00:00 2001 From: is-leplus <3210209742@qq.com> Date: Fri, 19 Dec 2025 12:07:57 +0800 Subject: [PATCH 1/7] Update ui_handler.py --- src/image_object_detection/ui_handler.py | 211 +++++++++++++---------- 1 file changed, 120 insertions(+), 91 deletions(-) diff --git a/src/image_object_detection/ui_handler.py b/src/image_object_detection/ui_handler.py index 4723def8d2..2070788af4 100644 --- a/src/image_object_detection/ui_handler.py +++ b/src/image_object_detection/ui_handler.py @@ -1,22 +1,32 @@ # ui_handler.py -# 功能:统一处理用户交互逻辑,支持命令行参数和交互式菜单两种模式 +# 功能:用户交互调度中心(User Interface Handler) +# 职责: +# - 提供命令行接口(CLI)和交互式菜单两种启动方式 +# - 解析用户输入(图像路径 / 摄像头指令) +# - 验证文件路径是否存在、可读、格式有效 +# - 调度静态图像检测 或 实时摄像头检测 +# - 处理用户中断(Ctrl+C)并优雅退出 +# - 保存检测结果图像并反馈保存状态 +# +# 设计原则: +# - 用户友好:错误提示具体到“文件不存在”、“无权限”、“格式不支持” +# - 安全兜底:即使用户输错路径,也不崩溃,而是返回主菜单 +# - 松耦合:依赖 DetectionEngine 和 CameraDetector,但不硬编码其内部逻辑 +# - 可扩展:支持未来新增模式(如视频文件检测) import os import cv2 import argparse -from detection_engine import DetectionEngine +import traceback + +from detection_engine import DetectionEngine, ModelLoadError +from camera_detector import CameraOpenError def parse_args(): """ - 解析命令行参数。 - - 支持两种运行模式: - --image : 指定静态图像路径进行检测 - --camera : 启动实时摄像头检测 - - 返回: - argparse.Namespace: 解析后的参数对象 + 解析命令行参数,支持 --image 或 --camera 两种模式。 + 返回 argparse.Namespace 对象。 """ parser = argparse.ArgumentParser(description="YOLOv8 Detection System") parser.add_argument("--image", type=str, help="Path to input image file") @@ -26,139 +36,157 @@ def parse_args(): class UIHandler: """ - 用户界面处理器类。 - 负责协调命令行参数、交互式菜单、图像/摄像头检测流程, - 是整个应用的调度中心。 + 用户界面控制器。 + 初始化时加载模型,失败则立即退出。 + 支持 CLI 模式和交互式菜单。 """ def __init__(self, config): """ - 初始化 UI 处理器。 - - 参数: - config (Config): 配置对象,包含模型路径、阈值、摄像头索引等参数 + 初始化 UIHandler。 + 若 DetectionEngine 初始化失败(如模型加载错误),打印错误并退出。 """ self.config = config - # 初始化检测引擎(加载 YOLO 模型) - self.engine = DetectionEngine( - model_path=config.model_path, - conf_threshold=config.confidence_threshold - ) + try: + self.engine = DetectionEngine( + model_path=config.model_path, + conf_threshold=config.confidence_threshold + ) + except ModelLoadError as e: + print(f"❌ Fatal: Failed to initialize detection engine: {e}") + raise SystemExit(1) def run(self): """ - 主运行入口。 - 优先检查命令行参数;若无,则进入交互式菜单。 + 主流程入口: + - 若有 --image 参数 → 静态检测 + - 若有 --camera 参数 → 摄像头检测 + - 否则 → 交互式菜单 """ args = parse_args() - if args.image is not None: print(f"[CLI Mode] Detecting static image: {args.image}") - self._run_static_detection(image_path=args.image) + self._run_static_detection(args.image) elif args.camera: print("[CLI Mode] Starting live camera detection...") self._run_camera_detection() else: - # 无命令行参数时,启动交互式菜单 self._interactive_menu() def _interactive_menu(self): """ - 显示交互式主菜单,供用户选择操作模式。 - 支持选项: - 1. 静态图像检测(可选默认图或自定义路径) - 2. 实时摄像头检测 - 3. 退出程序 + 显示交互式文本菜单,处理用户选择。 + 支持 Ctrl+C 中断,无效输入递归重试。 """ - print("=== YOLO Detection System ===") - print("1. Static Image Detection") - print("2. Live Camera Detection") - print("3. Exit") - choice = input("Please select an option (1-3): ").strip() + try: + print("\n" + "=" * 40) + print("🚀 YOLOv8 Detection System") + print("=" * 40) + print("1. Static Image Detection") + print("2. Live Camera Detection") + print("3. Exit") + choice = input("Please select an option (1-3): ").strip() + except KeyboardInterrupt: + print("\nUser cancelled. Exiting...") + return if choice == "1": self._choose_image_source() elif choice == "2": self._run_camera_detection() elif choice == "3": - print("Exiting program.") + print("Goodbye!") else: print("Invalid option. Please enter 1, 2, or 3.") + self._interactive_menu() def _choose_image_source(self): """ - 子菜单:让用户选择使用默认测试图像还是输入自定义路径。 - 默认路径硬编码为桌面的 test.jpg(适用于快速测试)。 + 子菜单:让用户选择默认测试图或自定义路径。 + 对自定义路径进行 ~ 展开和不可见字符清理。 + 分级验证路径有效性(存在性、可读性)。 """ - default_image_path = self.config.default_image_path # 使用配置中的默认图片路径 + default_path = self.config.default_image_path print("\n--- Static Image Detection ---") - print(f"a) Use default test image at: {default_image_path}") + print(f"a) Use default test image at: {default_path}") print("b) Enter custom image path") - sub_choice = input("Choose (a/b): ").strip().lower() + try: + sub_choice = input("Choose (a/b): ").strip().lower() + except KeyboardInterrupt: + return if sub_choice == "a": - # 检查默认图像是否存在 - if not os.path.exists(default_image_path): - print(f"\n⚠️ Default image not found at:\n {default_image_path}") - print("💡 Please place a 'test.jpg' file in the specified location, or choose option (b).") + if not os.path.exists(default_path): + print(f"⚠️ Default image not found: {default_path}") + print("💡 Place 'test.jpg' in the 'data/' folder or choose (b).") return - print(f"Using default image: {default_image_path}") - self._run_static_detection(image_path=default_image_path) - + self._run_static_detection(default_path) elif sub_choice == "b": - # 获取用户输入的路径,并展开 ~ 符号(如 ~/Pictures/img.jpg) - custom_path = input("Enter full or relative image path: ").strip() - custom_path = os.path.expanduser(custom_path) - # 移除可能的不可见 Unicode 控制字符(特别是从 Windows 复制的路径) - custom_path = ''.join(ch for ch in custom_path if ord(ch) != 0x202A) + try: + custom_path = input("Enter image path: ").strip() + custom_path = os.path.expanduser(custom_path) + # 清理从某些系统复制时可能带入的不可见 Unicode 控制字符(如 U+202A) + custom_path = ''.join(ch for ch in custom_path if ord(ch) != 0x202A) + except KeyboardInterrupt: + return + if not os.path.exists(custom_path): - print(f"❌ Error: File not found at: {custom_path}") + print(f"❌ File not found: {custom_path}") + return + if not os.access(custom_path, os.R_OK): + print(f"❌ Permission denied: {custom_path}") return - self._run_static_detection(image_path=custom_path) + self._run_static_detection(custom_path) else: print("Invalid choice. Returning to main menu.") def _run_static_detection(self, image_path): - """ - 执行静态图像检测流程。 - - 参数: - image_path (str): 待检测图像的完整路径 + """ + 执行单张图像检测: + - 使用 cv2.imread 读取 + - 若失败,分级诊断原因(路径?权限?格式?) + - 显示结果窗口,等待按键关闭 + - 自动保存结果图(原文件名 + "_detected" + 原扩展名) """ print(f"🔍 Detecting objects in: {image_path}") + frame = cv2.imread(image_path) + if frame is None: + # 分级诊断 imread 失败原因 + if not os.path.exists(image_path): + print(f"❌ Path does not exist: {image_path}") + elif not os.access(image_path, os.R_OK): + print(f"❌ No read permission: {image_path}") + else: + print(f"❌ Unsupported or corrupted image format: {image_path}") + return + + annotated_frame, _ = self.engine.detect(frame) + + window_name = "YOLO Detection Result" + cv2.namedWindow(window_name, cv2.WINDOW_NORMAL) + cv2.imshow(window_name, annotated_frame) + print("Press any key to close.") + cv2.waitKey(0) + cv2.destroyAllWindows() + + # 智能保留原扩展名(JPG/PNG) + ext = ".jpg" if image_path.lower().endswith(".jpg") else ".png" + save_path = image_path.replace(ext, f"_detected{ext}") try: - # 直接读取图像 - frame = cv2.imread(image_path) - if frame is None: - print(f"❌ Failed to load image from: {image_path}") - return - - # 使用已有的 self.engine(DetectionEngine)进行检测 - annotated_frame, results = self.engine.detect(frame) - - # 显示可缩放窗口 - window_name = "YOLO Detection Result" - cv2.namedWindow(window_name, cv2.WINDOW_NORMAL) # 👈 关键修改:启用可缩放窗口 - cv2.imshow(window_name, annotated_frame) - print("Detection completed. Press any key to close the window.") - cv2.waitKey(0) - cv2.destroyAllWindows() - - # 可选:保存结果 - save_path = image_path.replace(".jpg", "_detected.jpg").replace(".png", "_detected.png") - cv2.imwrite(save_path, annotated_frame) - print(f"Result saved to: {save_path}") - + success = cv2.imwrite(save_path, annotated_frame) + if success: + print(f"✅ Result saved to: {save_path}") + else: + print("❌ Failed to save result (OpenCV write error)") except Exception as e: - print(f"❌ Detection failed: {e}") - import traceback - traceback.print_exc() # 打印完整错误栈,便于调试 + print(f"⚠️ Failed to save result: {e}") def _run_camera_detection(self): """ - 执行实时摄像头检测流程。 - 使用配置中的摄像头索引和输出间隔参数。 + 启动实时摄像头检测。 + 动态创建 CameraDetector 实例并运行。 + 捕获摄像头专属异常和其他未预期错误。 """ try: from camera_detector import CameraDetector @@ -167,7 +195,8 @@ def _run_camera_detection(self): output_interval=self.config.output_interval ) detector.start_detection(camera_index=self.config.camera_index) + except CameraOpenError as e: + print(f"❌ Camera error: {e}") except Exception as e: - print(f"❌ Camera detection failed: {e}") - import traceback + print(f"💥 Camera detection failed: {e}") traceback.print_exc() From 32dc5f47a36799864e475bbc294f9eaf453a1e71 Mon Sep 17 00:00:00 2001 From: is-leplus <3210209742@qq.com> Date: Fri, 19 Dec 2025 12:08:27 +0800 Subject: [PATCH 2/7] Update main.py --- src/image_object_detection/main.py | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/image_object_detection/main.py b/src/image_object_detection/main.py index 7862583f82..ea54255436 100644 --- a/src/image_object_detection/main.py +++ b/src/image_object_detection/main.py @@ -18,10 +18,22 @@ def main(): 3. 启动交互流程(支持命令行参数或交互式菜单) """ config = Config() # 创建配置实例 - ui_handler = UIHandler(config) # 传入配置,初始化 UI 处理器 - ui_handler.run() # 启动主运行逻辑 + handler = UIHandler(config) # 传入配置,初始化 UI 处理器 + try: + handler.run() + except KeyboardInterrupt: + # 用户按下 Ctrl+C:安静退出,不显示 traceback + print("\nProgram interrupted by user. Exiting gracefully...") + except SystemExit: + # 由 UIHandler 或 DetectionEngine 主动触发的退出(如模型加载失败) + pass + except Exception as e: + # 捕获未预期的顶层异常(开发阶段保留,生产环境可记录日志) + print(f"Unexpected error in main: {e}") + raise # 重新抛出以便调试 # 确保脚本直接运行时才执行 main(),便于模块复用和测试 if __name__ == "__main__": main() + From 714beec6617a0dfcb4034caccaf4783c15793c0a Mon Sep 17 00:00:00 2001 From: is-leplus <3210209742@qq.com> Date: Fri, 19 Dec 2025 12:08:50 +0800 Subject: [PATCH 3/7] Update detection_engine.py --- .../detection_engine.py | 47 +++++++++++++------ 1 file changed, 33 insertions(+), 14 deletions(-) diff --git a/src/image_object_detection/detection_engine.py b/src/image_object_detection/detection_engine.py index 8c0d881b7a..5c11eaa3c9 100644 --- a/src/image_object_detection/detection_engine.py +++ b/src/image_object_detection/detection_engine.py @@ -4,8 +4,13 @@ from ultralytics import YOLO import io import sys +import os +class ModelLoadError(Exception): + """模型加载失败专用异常""" + pass + class DetectionEngine: """ 目标检测引擎类。 @@ -46,18 +51,30 @@ def _load_model(self): sys.stderr = io.StringIO() try: - # 加载模型(若为官方模型且未下载,会自动联网下载) - print(f"尝试加载模型: {self.model_path}") # 打印调试信息 - model = YOLO(self.model_path) + # 判断是本地文件还是官方模型名 + if os.path.isfile(self.model_path): + model = YOLO(self.model_path) + else: + # 尝试作为 Ultralytics 官方模型加载(会自动下载) + model = YOLO(self.model_path) + return model + except FileNotFoundError as e: + raise ModelLoadError(f"Model file not found: {self.model_path}") from e + except RuntimeError as e: + msg = str(e) + if "CUDA out of memory" in msg: + raise ModelLoadError( + "GPU memory insufficient. Try using CPU or a smaller model (e.g., yolov8n.pt)." + ) from e + elif "AssertionError" in msg and ("model" in msg or "state_dict" in msg): + raise ModelLoadError(f"Corrupted or incompatible model weights: {self.model_path}") from e + else: + raise ModelLoadError(f"Runtime error during model loading: {msg}") from e except Exception as e: - print(f"加载模型失败: {e}") # 打印异常信息 - raise e # 重新抛出异常以便进一步处理 + raise ModelLoadError(f"Unexpected error loading YOLO model: {e}") from e finally: - # 确保无论是否出错,都恢复原始输出流 - sys.stdout = old_stdout - sys.stderr = old_stderr - - return model + sys.stdout, sys.stderr = old_stdout, old_stderr + def detect(self, frame): """ @@ -86,13 +103,15 @@ def detect(self, frame): try: # 执行推理:传入图像、置信度阈值,并关闭详细日志(verbose=False) results = self.model(frame, conf=self.conf_threshold, verbose=False) + annotated_frame = results[0].plot() + return annotated_frame, results + except Exception as e: + # 不抛出异常,而是返回原图以维持流程 + print(f"⚠️ Warning: Detection failed on current frame: {e}") + return frame.copy(), [] finally: # 恢复标准输出 sys.stdout = old_stdout sys.stderr = old_stderr - # 使用 YOLO 内置的 plot() 方法生成带标注的图像(numpy array, HWC) - annotated_frame = results[0].plot() # results 总是包含至少一个元素 - - return annotated_frame, results From 2006c6bec6cc3f6d19e60f470df1eca0af76adfb Mon Sep 17 00:00:00 2001 From: is-leplus <3210209742@qq.com> Date: Fri, 19 Dec 2025 12:09:16 +0800 Subject: [PATCH 4/7] Update config.py --- src/image_object_detection/config.py | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/image_object_detection/config.py b/src/image_object_detection/config.py index bb51feacaa..5a55c8bd3a 100644 --- a/src/image_object_detection/config.py +++ b/src/image_object_detection/config.py @@ -3,6 +3,9 @@ import os +class ConfigError(Exception): + """配置相关异常的基类""" + pass class Config: """ @@ -10,7 +13,6 @@ class Config: 所有核心参数(如模型路径、默认图像路径、阈值等)集中在此初始化, 便于维护和部署时调整。 """ - def __init__(self): # 获取当前 config.py 文件所在目录的绝对路径 # 使用 os.path.abspath 确保路径在不同操作系统下一致 @@ -18,10 +20,8 @@ def __init__(self): # 默认测试图像路径:位于项目根目录下的 data/test.jpg # 若用户未指定图像路径,系统将尝试加载此文件 - base_dir = os.path.dirname(os.path.abspath(__file__)) - self.default_image_path = os.path.join(base_dir, "data", "test.jpg") #注意:项目根目录下的data文件!!! + self.default_image_path = os.path.join(base_dir, "data", "test.jpg") - # YOLO 模型权重文件路径 # 支持: # - 内置模型名(如 "yolov8n.pt",首次运行会自动下载) @@ -31,7 +31,7 @@ def __init__(self): # 目标检测的置信度阈值 # 只有置信度 ≥ 此值的检测框才会被保留和显示 # 范围:0.0 ~ 1.0,值越高,结果越严格 - self.confidence_threshold = 0.35 + self.confidence_threshold = 0.25 # 摄像头设备索引 # 通常 0 表示内置摄像头,外接摄像头可能为 1、2 等 @@ -42,3 +42,14 @@ def __init__(self): self.output_interval = 1.0 + # 验证置信度阈值 + if not (0.0 <= self.confidence_threshold <= 1.0): + raise ConfigError("confidence_threshold must be in range [0.0, 1.0]") + + # 验证摄像头索引 + if not isinstance(self.camera_index, int) or self.camera_index < 0: + raise ConfigError("camera_index must be a non-negative integer") + + # 验证输出间隔 + if self.output_interval <= 0: + raise ConfigError("output_interval must be positive") From d8a0bc434169bebd3ae6fa2fc408ec568f0dfd31 Mon Sep 17 00:00:00 2001 From: is-leplus <3210209742@qq.com> Date: Fri, 19 Dec 2025 12:09:39 +0800 Subject: [PATCH 5/7] Update camera_detector.py --- src/image_object_detection/camera_detector.py | 262 +++++++++++++----- 1 file changed, 197 insertions(+), 65 deletions(-) diff --git a/src/image_object_detection/camera_detector.py b/src/image_object_detection/camera_detector.py index 40fb1bb87e..ef0c67d77c 100644 --- a/src/image_object_detection/camera_detector.py +++ b/src/image_object_detection/camera_detector.py @@ -1,121 +1,253 @@ # camera_detector.py -# 功能:封装基于摄像头的实时目标检测流程,支持帧保存与 FPS 显示 +# 功能:封装基于摄像头的实时目标检测流程 +# 特性: +# - 支持 FPS(帧率)动态统计与输出 +# - 支持按 's' 键保存当前检测帧 +# - 支持按 'q' 键优雅退出 +# - 自动创建可缩放 OpenCV 窗口 +# - 异常安全:确保摄像头和窗口资源被正确释放 +# - 兼容模型推理失败场景(不会因单帧错误崩溃) + +import cv2 # OpenCV:用于摄像头读取、图像显示与保存 +import time # 用于时间戳生成和 FPS 计算 +import os # 用于文件路径操作(保存帧时) +import traceback # 用于打印完整的错误调用栈,便于调试 + + +# ======================== +# 🔧 自定义异常类(提升错误语义清晰度) +# ======================== + +class CameraOpenError(Exception): + """ + 摄像头设备无法打开时抛出的专用异常。 + 用于区分“设备不存在”、“权限不足”、“已被占用”等场景。 + """ + pass -import cv2 -import time -import traceback +# ======================== +# 🎥 主检测器类 +# ======================== class CameraDetector: """ - 摄像头实时检测器类。 - 使用传入的 detection_engine(如 YOLO 模型)对摄像头视频流进行逐帧推理, - 并提供可视化、FPS 统计、帧保存等功能。 + 摄像头实时目标检测器。 + + 职责: + - 管理 VideoCapture 生命周期 + - 调用外部 detection_engine 执行每帧推理 + - 显示带标注的视频流 + - 响应用户键盘输入(退出/保存) + - 实时计算并输出 FPS(帧率) + - 安全保存检测结果帧 + + 设计原则: + - **松耦合**:不依赖具体模型,只依赖实现了 detect(frame) 接口的对象 + - **健壮性**:即使某帧推理失败,也不中断整个检测循环 + - **资源安全**:无论是否发生异常,都确保释放摄像头和关闭窗口 """ def __init__(self, detection_engine, output_interval=1.0): """ - 初始化检测器。 + 初始化摄像头检测器。 参数: - detection_engine: 实现 detect(frame) 方法的对象,用于执行目标检测 - output_interval (float): FPS 输出的时间间隔(秒),默认每 1 秒打印一次 + detection_engine (object): + 必须实现 detect(frame) 方法,返回 (annotated_frame, results)。 + 通常为 DetectionEngine 实例。 + + output_interval (float, optional): + FPS 信息的输出间隔(单位:秒)。默认每 1 秒打印一次。 + 设置过小会导致控制台刷屏;过大则反馈延迟。 """ - self.engine = detection_engine # 外部传入的检测引擎(如 DetectionEngine 实例) - self.output_interval = output_interval # FPS 打印间隔(秒) - self.last_output_time = 0 # 上次打印 FPS 的时间戳 - self.frame_count = 0 # 自上次打印以来处理的帧数 - self.window_name = "YOLO_Live_Detection" # OpenCV 窗口名称(英文,避免编码问题) + self.engine = detection_engine # 外部传入的检测引擎(如 YOLO 封装) + self.output_interval = output_interval # FPS 打印的时间间隔(秒) + self.last_output_time = 0 # 上次打印 FPS 的 Unix 时间戳 + self.frame_count = 0 # 自上次打印以来成功处理的帧数 + self.window_name = "YOLO_Live_Detection" # OpenCV 窗口标题(使用英文避免编码问题) def start_detection(self, camera_index=0): """ - 启动摄像头并开始实时检测。 + 启动摄像头并进入实时检测主循环。 参数: - camera_index (int): 摄像头设备索引,默认为 0(主摄像头) + camera_index (int, optional): + 摄像头设备索引。通常: + - 0:内置摄像头(笔记本) + - 1、2...:外接 USB 摄像头 + 若指定设备不可用,将抛出 CameraOpenError。 + + 流程概览: + 1. 尝试打开摄像头设备 + 2. 创建可调整大小的 OpenCV 显示窗口 + 3. 进入无限循环: + a. 读取一帧 + b. 调用检测引擎推理 + c. 显示结果 + d. 监听键盘事件(退出/保存) + e. 更新 FPS 统计 + 4. 捕获所有异常并记录 + 5. finally 块确保资源释放 + + 注意: + - 使用 cv2.waitKey(1) 实现非阻塞键盘监听 + - 即使 detect() 返回无效图像,也尝试显示(避免黑屏) """ - # 尝试打开指定索引的摄像头 - cap = cv2.VideoCapture(camera_index) - if not cap.isOpened(): - print(f"Error: Cannot open camera {camera_index}") - return - - print("Starting live detection. Press 'q' to quit, 's' to save frame.") - # 创建可调整大小的 OpenCV 窗口(只需创建一次) - cv2.namedWindow(self.window_name, cv2.WINDOW_NORMAL) - + cap = None # 初始化为 None,便于 finally 块安全检查 try: + # ---------------------------- + # 🔌 步骤 1:打开摄像头设备 + # ---------------------------- + cap = cv2.VideoCapture(camera_index) + if not cap.isOpened(): + # 如果无法打开,抛出自定义异常,携带上下文信息 + raise CameraOpenError( + f"Cannot open camera device {camera_index}. " + "Possible reasons: " + "- Device does not exist; " + "- Already in use by another application; " + "- Insufficient permissions (e.g., on Linux)." + ) + + # ---------------------------- + # 🖼️ 步骤 2:创建显示窗口 + # ---------------------------- + # 使用 WINDOW_NORMAL 允许用户手动缩放窗口(对高分辨率摄像头友好) + cv2.namedWindow(self.window_name, cv2.WINDOW_NORMAL) + print("Starting live detection. Press 'q' to quit, 's' to save frame.") + + # ---------------------------- + # 🔁 步骤 3:主检测循环 + # ---------------------------- while True: - # 从摄像头读取一帧 + # 从摄像头读取一帧(BGR 格式,HWC 布局) ret, frame = cap.read() if not ret: - print("Warning: Failed to read frame from camera") - break + # 读取失败常见于:摄像头被拔出、驱动崩溃、USB 断开 + print("⚠️ Warning: Failed to read frame from camera. " + "Camera may have been disconnected.") + break # 退出循环,进入清理阶段 + # 获取当前时间戳,用于 FPS 计算 current_time = time.time() - # 使用检测引擎对当前帧进行推理,返回带标注的图像和原始结果 - annotated_frame, results = self.engine.detect(frame) + # ---------------------------- + # 🧠 步骤 4:执行目标检测 + # ---------------------------- + # 调用外部引擎进行推理。即使内部出错,detect() 也会返回原图(见 detection_engine.py) + annotated_frame, _ = self.engine.detect(frame) - # 安全检查:确保返回的图像有效 - if annotated_frame is None or annotated_frame.size == 0: - print("Warning: Invalid detection result") - continue + # 安全检查:防止 OpenCV 显示空图像导致崩溃 + if annotated_frame.size == 0: + print("⚠️ Warning: Received empty annotated frame. Skipping display.") + continue # 跳过当前帧,继续下一帧 - # 显示带检测框的图像 + # ---------------------------- + # 👁️ 步骤 5:显示结果 + # ---------------------------- cv2.imshow(self.window_name, annotated_frame) - # 检查键盘输入(等待 1 毫秒) + # ---------------------------- + # ⌨️ 步骤 6:监听键盘输入(非阻塞) + # ---------------------------- + # waitKey(1) 表示等待 1 毫秒,若无按键则返回 -1 + # & 0xFF 是为了兼容某些系统返回高位字节的情况 key = cv2.waitKey(1) & 0xFF - if key == ord('q'): # 按 'q' 退出 + if key == ord('q'): # 'q' 键:退出程序 + print("User pressed 'q'. Exiting live detection...") break - elif key == ord('s'): # 按 's' 保存当前帧 + elif key == ord('s'): # 's' 键:保存当前帧 self.save_frame(annotated_frame) - # 更新 FPS 统计并按需打印 + # ---------------------------- + # 📊 步骤 7:更新并输出 FPS + # ---------------------------- self._print_fps_if_needed(current_time) self.frame_count += 1 + # ---------------------------- + # 🚨 异常处理区 + # ---------------------------- except KeyboardInterrupt: - print("\nDetection interrupted by user.") + # 用户按下 Ctrl+C 中断程序 + print("\nUser interrupted live detection via Ctrl+C.") + except CameraOpenError as e: + # 摄像头打开失败(由我们主动抛出) + print(f"❌ Camera error: {e}") except Exception as e: - print(f"Unexpected error during detection: {e}") - traceback.print_exc() # 打印完整错误栈,便于调试 + # 捕获其他未预期的异常(如 OpenCV 内部错误) + print(f"💥 Unexpected error during camera detection loop: {e}") + traceback.print_exc() # 打印完整错误栈,便于开发者定位问题 + + # ---------------------------- + # ♻️ 资源清理区(无论是否出错都会执行) + # ---------------------------- finally: - # 确保资源被正确释放 - cap.release() + # 安全释放摄像头资源(避免“设备忙”错误) + if cap is not None and cap.isOpened(): + cap.release() + print("✅ Camera resource released.") + + # 关闭所有 OpenCV 窗口(防止残留窗口) cv2.destroyAllWindows() - print("Camera released and windows closed.") + print("AllWindows closed. Live detection terminated.") def _print_fps_if_needed(self, current_time): """ - 根据设定的时间间隔计算并打印当前 FPS(帧率)。 + 根据预设的时间间隔,计算并打印当前 FPS(Frames Per Second)。 参数: - current_time (float): 当前时间戳(秒) - """ - # 判断是否到达输出间隔 - if current_time - self.last_output_time >= self.output_interval: - # 避免除零:首次运行时 last_output_time 为 0,不计算 FPS - fps = self.frame_count / (current_time - self.last_output_time) if self.last_output_time > 0 else 0 - print(f"FPS: {fps:.2f}") + current_time (float): 当前 Unix 时间戳(由 time.time() 获取) - # 重置计时器和帧计数器 + 逻辑说明: + - 首次运行时 last_output_time 为 0,跳过 FPS 计算(避免除零) + - 达到 output_interval 后,计算平均 FPS 并重置计数器 + - FPS = 处理帧数 / 时间间隔 + + 示例输出: + FPS: 28.45 + """ + elapsed = current_time - self.last_output_time + if elapsed >= self.output_interval: + if self.last_output_time > 0: # 避免除零(首次不计算) + fps = self.frame_count / elapsed + print(f"FPS: {fps:.2f}") # 保留两位小数 + # 重置计时器和帧计数器,开始下一轮统计 self.last_output_time = current_time self.frame_count = 0 def save_frame(self, frame): """ - 将当前帧保存为 JPEG 图像文件,文件名包含时间戳。 + 将当前检测帧保存为 JPEG 图像文件。 参数: - frame (np.ndarray): 要保存的图像数组(BGR 格式) + frame (np.ndarray): BGR 格式的图像数组(来自 OpenCV) + + 文件命名规则: + saved_frame_.jpg + 例如:saved_frame_1734567890.jpg + + 优势: + - 时间戳确保文件名全局唯一 + - 避免覆盖用户已有文件 + + 异常处理: + - 捕获写入失败(如磁盘满、路径无权限) + - 不中断主流程,仅打印警告 """ - import os # 延迟导入(仅在此方法中使用) - timestamp = int(time.time()) # 使用 Unix 时间戳确保文件名唯一 + timestamp = int(time.time()) # 获取当前秒级时间戳 filename = f"saved_frame_{timestamp}.jpg" - success = cv2.imwrite(filename, frame) - if success: - print(f"Frame saved as {filename}") - else: - print("Failed to save frame") + + try: + # 使用 OpenCV 将图像写入磁盘(JPEG 格式,质量默认) + success = cv2.imwrite(filename, frame) + if success: + # 获取绝对路径便于用户定位文件 + abs_path = os.path.abspath(filename) + print(f"✅ Frame saved successfully: {abs_path}") + else: + print(f"❌ OpenCV failed to write image to: {filename}") + except Exception as e: + # 捕获文件系统相关异常(如权限、磁盘空间) + print(f"❌ Error saving frame: {e}") From 434356357e214a26c9d1bf8a85e756f3b7a63c6a Mon Sep 17 00:00:00 2001 From: is-leplus <3210209742@qq.com> Date: Fri, 19 Dec 2025 22:46:27 +0800 Subject: [PATCH 6/7] Update ui_handler.py --- src/image_object_detection/ui_handler.py | 64 +++++++++++++++++++++--- 1 file changed, 57 insertions(+), 7 deletions(-) diff --git a/src/image_object_detection/ui_handler.py b/src/image_object_detection/ui_handler.py index 2070788af4..e7c5a96c7d 100644 --- a/src/image_object_detection/ui_handler.py +++ b/src/image_object_detection/ui_handler.py @@ -2,16 +2,16 @@ # 功能:用户交互调度中心(User Interface Handler) # 职责: # - 提供命令行接口(CLI)和交互式菜单两种启动方式 -# - 解析用户输入(图像路径 / 摄像头指令) +# - 解析用户输入(图像路径 / 摄像头指令 / 批量目录) # - 验证文件路径是否存在、可读、格式有效 -# - 调度静态图像检测 或 实时摄像头检测 +# - 调度静态图像检测、实时摄像头检测 或 批量图像检测 # - 处理用户中断(Ctrl+C)并优雅退出 # - 保存检测结果图像并反馈保存状态 # # 设计原则: # - 用户友好:错误提示具体到“文件不存在”、“无权限”、“格式不支持” # - 安全兜底:即使用户输错路径,也不崩溃,而是返回主菜单 -# - 松耦合:依赖 DetectionEngine 和 CameraDetector,但不硬编码其内部逻辑 +# - 松耦合:依赖 DetectionEngine、CameraDetector 和 BatchDetector,但不硬编码其内部逻辑 # - 可扩展:支持未来新增模式(如视频文件检测) import os @@ -25,12 +25,13 @@ def parse_args(): """ - 解析命令行参数,支持 --image 或 --camera 两种模式。 + 解析命令行参数,支持 --image 、--camera 或 --batch 三种模式。 返回 argparse.Namespace 对象。 """ parser = argparse.ArgumentParser(description="YOLOv8 Detection System") parser.add_argument("--image", type=str, help="Path to input image file") parser.add_argument("--camera", action="store_true", help="Start live camera detection") + parser.add_argument("--batch", type=str, help="Path to input directory for batch detection") return parser.parse_args() @@ -61,6 +62,7 @@ def run(self): 主流程入口: - 若有 --image 参数 → 静态检测 - 若有 --camera 参数 → 摄像头检测 + - 若有 --batch 参数 → 批量检测 - 否则 → 交互式菜单 """ args = parse_args() @@ -70,6 +72,9 @@ def run(self): elif args.camera: print("[CLI Mode] Starting live camera detection...") self._run_camera_detection() + elif args.batch is not None: + print(f"[CLI Mode] Running batch detection on directory: {args.batch}") + self._run_batch_detection(args.batch) else: self._interactive_menu() @@ -84,8 +89,9 @@ def _interactive_menu(self): print("=" * 40) print("1. Static Image Detection") print("2. Live Camera Detection") - print("3. Exit") - choice = input("Please select an option (1-3): ").strip() + print("3. Batch Image Detection") + print("4. Exit") + choice = input("Please select an option (1-4): ").strip() except KeyboardInterrupt: print("\nUser cancelled. Exiting...") return @@ -95,9 +101,11 @@ def _interactive_menu(self): elif choice == "2": self._run_camera_detection() elif choice == "3": + self._run_batch_detection_interactive() + elif choice == "4": print("Goodbye!") else: - print("Invalid option. Please enter 1, 2, or 3.") + print("Invalid option. Please enter 1, 2, 3, or 4.") self._interactive_menu() def _choose_image_source(self): @@ -200,3 +208,45 @@ def _run_camera_detection(self): except Exception as e: print(f"💥 Camera detection failed: {e}") traceback.print_exc() + + def _run_batch_detection_interactive(self): + """ + 交互式批量检测:用户输入输入目录,自动将结果保存到同级 test_picture/ 目录。 + """ + try: + input_dir = input("Enter input directory path (e.g., ../data): ").strip() + input_dir = os.path.expanduser(input_dir) + # 清理不可见字符(如从 Windows 资源管理器复制的路径) + input_dir = ''.join(ch for ch in input_dir if ord(ch) != 0x202A) + except KeyboardInterrupt: + return + + if not os.path.isdir(input_dir): + print(f"❌ Directory not found: {input_dir}") + return + + # 默认输出目录:与输入目录同级的 test_picture/ + output_dir = os.path.join(input_dir, "test_picture") + self._run_batch_detection(input_dir, output_dir) + + def _run_batch_detection(self, input_dir, output_dir=None): + """ + 执行批量图像检测。 + 参数: + input_dir (str): 输入图像目录 + output_dir (str, optional): 输出目录,默认为 input_dir/test_picture + """ + if output_dir is None: + output_dir = os.path.join(input_dir, "test_picture") + + try: + from batch_detector import BatchDetector + detector = BatchDetector( + detection_engine=self.engine, + input_dir=input_dir, + output_dir=output_dir + ) + detector.run() + except Exception as e: + print(f"💥 Batch detection failed: {e}") + traceback.print_exc() From 1e8606c4609e07a0b4d3b001655e8cb233970520 Mon Sep 17 00:00:00 2001 From: is-leplus <3210209742@qq.com> Date: Fri, 19 Dec 2025 22:52:51 +0800 Subject: [PATCH 7/7] Create batch_detector.py --- src/image_object_detection/batch_detector.py | 57 ++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/image_object_detection/batch_detector.py diff --git a/src/image_object_detection/batch_detector.py b/src/image_object_detection/batch_detector.py new file mode 100644 index 0000000000..59332f8d85 --- /dev/null +++ b/src/image_object_detection/batch_detector.py @@ -0,0 +1,57 @@ +# batch_detector.py + +import os +import cv2 +from pathlib import Path +from detection_engine import DetectionEngine, ModelLoadError + + +class BatchDetector: + def __init__(self, detection_engine, input_dir, output_dir): + + self.engine = detection_engine + self.input_dir = Path(input_dir) + self.output_dir = Path(output_dir) + + self.image_extensions = {'.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.webp'} + + self.output_dir.mkdir(parents=True, exist_ok=True) + + if not self.input_dir.is_dir(): + raise ValueError(f"Input directory does not exist: {self.input_dir}") + + def run(self): + image_files = [ + f for f in self.input_dir.iterdir() + if f.is_file() and f.suffix.lower() in self.image_extensions + ] + + if not image_files: + print(f"⚠️ No valid image files found in {self.input_dir}") + return + + print(f"🔍 Found {len(image_files)} images. Starting batch detection...") + success_count = 0 + + for img_path in sorted(image_files): + try: + # 读取图像 + frame = cv2.imread(str(img_path)) + if frame is None: + print(f"❌ Failed to read image (corrupted or unsupported): {img_path.name}") + continue + + annotated_frame, _ = self.engine.detect(frame) + + output_path = self.output_dir / f"{img_path.stem}_detected{img_path.suffix}" + + if cv2.imwrite(str(output_path), annotated_frame): + print(f"✅ Saved: {output_path.name}") + success_count += 1 + else: + print(f"❌ Failed to save: {output_path}") + + except Exception as e: + print(f"💥 Error processing {img_path.name}: {e}") + + print(f"\n🎉 Batch detection completed. {success_count}/{len(image_files)} images processed successfully.")