From b9c6b341219175bc2baec4824a2e3fdd61f73b69 Mon Sep 17 00:00:00 2001 From: is-leplus <3210209742@qq.com> Date: Thu, 18 Dec 2025 15:49:05 +0800 Subject: [PATCH 1/5] Update ui_handler.py --- src/image_object_detection/ui_handler.py | 96 +++++++++++++++++++++--- 1 file changed, 84 insertions(+), 12 deletions(-) diff --git a/src/image_object_detection/ui_handler.py b/src/image_object_detection/ui_handler.py index 94a946921f..4723def8d2 100644 --- a/src/image_object_detection/ui_handler.py +++ b/src/image_object_detection/ui_handler.py @@ -1,26 +1,55 @@ # ui_handler.py +# 功能:统一处理用户交互逻辑,支持命令行参数和交互式菜单两种模式 + import os import cv2 import argparse from detection_engine import DetectionEngine -from image_detector import ImageDetector -from camera_detector import CameraDetector + def parse_args(): + """ + 解析命令行参数。 + + 支持两种运行模式: + --image : 指定静态图像路径进行检测 + --camera : 启动实时摄像头检测 + + 返回: + 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") return parser.parse_args() + class UIHandler: + """ + 用户界面处理器类。 + 负责协调命令行参数、交互式菜单、图像/摄像头检测流程, + 是整个应用的调度中心。 + """ + def __init__(self, config): + """ + 初始化 UI 处理器。 + + 参数: + config (Config): 配置对象,包含模型路径、阈值、摄像头索引等参数 + """ self.config = config + # 初始化检测引擎(加载 YOLO 模型) self.engine = DetectionEngine( model_path=config.model_path, conf_threshold=config.confidence_threshold ) def run(self): + """ + 主运行入口。 + 优先检查命令行参数;若无,则进入交互式菜单。 + """ args = parse_args() if args.image is not None: @@ -30,14 +59,21 @@ def run(self): print("[CLI Mode] Starting live camera detection...") self._run_camera_detection() else: + # 无命令行参数时,启动交互式菜单 self._interactive_menu() def _interactive_menu(self): + """ + 显示交互式主菜单,供用户选择操作模式。 + 支持选项: + 1. 静态图像检测(可选默认图或自定义路径) + 2. 实时摄像头检测 + 3. 退出程序 + """ 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() if choice == "1": @@ -50,46 +86,82 @@ def _interactive_menu(self): print("Invalid option. Please enter 1, 2, or 3.") def _choose_image_source(self): - """让用户选择使用默认图还是自定义路径""" - default_image_path = r"C:\Users\apple\OneDrive\桌面\test.jpg" - + """ + 子菜单:让用户选择使用默认测试图像还是输入自定义路径。 + 默认路径硬编码为桌面的 test.jpg(适用于快速测试)。 + """ + default_image_path = self.config.default_image_path # 使用配置中的默认图片路径 print("\n--- Static Image Detection ---") print(f"a) Use default test image at: {default_image_path}") print("b) Enter custom image path") sub_choice = input("Choose (a/b): ").strip().lower() 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(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).") return print(f"Using default image: {default_image_path}") self._run_static_detection(image_path=default_image_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) if not os.path.exists(custom_path): print(f"❌ Error: File not found at: {custom_path}") return self._run_static_detection(image_path=custom_path) + else: print("Invalid choice. Returning to main menu.") def _run_static_detection(self, image_path): - """执行静态图像检测""" + """ + 执行静态图像检测流程。 + + 参数: + image_path (str): 待检测图像的完整路径 + """ print(f"🔍 Detecting objects in: {image_path}") try: - detector = ImageDetector(self.engine) - detector.detect_static_image(image_path) + # 直接读取图像 + 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}") + except Exception as e: print(f"❌ Detection failed: {e}") import traceback - traceback.print_exc() + traceback.print_exc() # 打印完整错误栈,便于调试 def _run_camera_detection(self): + """ + 执行实时摄像头检测流程。 + 使用配置中的摄像头索引和输出间隔参数。 + """ try: + from camera_detector import CameraDetector detector = CameraDetector( detection_engine=self.engine, output_interval=self.config.output_interval From 75ef7c0d1a11f3f3db939e8e6e48178c1d061443 Mon Sep 17 00:00:00 2001 From: is-leplus <3210209742@qq.com> Date: Thu, 18 Dec 2025 15:50:50 +0800 Subject: [PATCH 2/5] Update config.py --- src/image_object_detection/config.py | 34 +++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/src/image_object_detection/config.py b/src/image_object_detection/config.py index 3a2599f6f2..277510f4c5 100644 --- a/src/image_object_detection/config.py +++ b/src/image_object_detection/config.py @@ -1,13 +1,41 @@ # config.py +# 功能:定义项目全局配置参数,便于统一管理和修改 + import os + class Config: + """ + 应用程序的配置类。 + 所有核心参数(如模型路径、默认图像路径、阈值等)集中在此初始化, + 便于维护和部署时调整。 + """ + def __init__(self): - # 获取当前脚本所在目录(更可靠) + # 获取当前 config.py 文件所在目录的绝对路径 + # 使用 os.path.abspath 确保路径在不同操作系统下一致 base_dir = os.path.dirname(os.path.abspath(__file__)) - self.default_image_path = os.path.join(base_dir, "data", "test.jpg") - + + # 默认测试图像路径:位于项目根目录下的 data/test.jpg + # 若用户未指定图像路径,系统将尝试加载此文件 + self.default_image_path = r"C:\Users\apple\OneDrive\桌面\test.jpg" + + # YOLO 模型权重文件路径 + # 支持: + # - 内置模型名(如 "yolov8n.pt",首次运行会自动下载) + # - 自定义训练模型的相对或绝对路径(如 "runs/detect/train/weights/best.pt") self.model_path = "yolov8n.pt" + + # 目标检测的置信度阈值 + # 只有置信度 ≥ 此值的检测框才会被保留和显示 + # 范围:0.0 ~ 1.0,值越高,结果越严格 self.confidence_threshold = 0.25 + + # 摄像头设备索引 + # 通常 0 表示内置摄像头,外接摄像头可能为 1、2 等 self.camera_index = 0 + + # FPS(帧率)输出的时间间隔(单位:秒) + # 例如设为 1.0 表示每秒打印一次当前处理速度 self.output_interval = 1.0 + From b084f6b08b6bbe8ccd52fd812d0128d2d1de3e83 Mon Sep 17 00:00:00 2001 From: is-leplus <3210209742@qq.com> Date: Thu, 18 Dec 2025 15:51:40 +0800 Subject: [PATCH 3/5] Update camera_detector.py --- src/image_object_detection/camera_detector.py | 92 ++++++++++++++----- 1 file changed, 70 insertions(+), 22 deletions(-) diff --git a/src/image_object_detection/camera_detector.py b/src/image_object_detection/camera_detector.py index 466e923f15..40fb1bb87e 100644 --- a/src/image_object_detection/camera_detector.py +++ b/src/image_object_detection/camera_detector.py @@ -1,70 +1,118 @@ # camera_detector.py +# 功能:封装基于摄像头的实时目标检测流程,支持帧保存与 FPS 显示 + import cv2 import time import traceback + class CameraDetector: + """ + 摄像头实时检测器类。 + 使用传入的 detection_engine(如 YOLO 模型)对摄像头视频流进行逐帧推理, + 并提供可视化、FPS 统计、帧保存等功能。 + """ + def __init__(self, detection_engine, output_interval=1.0): - self.engine = detection_engine - self.output_interval = output_interval - self.last_output_time = 0 - self.frame_count = 0 - self.window_name = "YOLO_Live_Detection" # 👈 英文窗口名 - + """ + 初始化检测器。 + + 参数: + detection_engine: 实现 detect(frame) 方法的对象,用于执行目标检测 + output_interval (float): 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 窗口名称(英文,避免编码问题) + def start_detection(self, camera_index=0): + """ + 启动摄像头并开始实时检测。 + + 参数: + camera_index (int): 摄像头设备索引,默认为 0(主摄像头) + """ + # 尝试打开指定索引的摄像头 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.") - cv2.namedWindow(self.window_name, cv2.WINDOW_NORMAL) # 创建一次即可 - + # 创建可调整大小的 OpenCV 窗口(只需创建一次) + cv2.namedWindow(self.window_name, cv2.WINDOW_NORMAL) + try: while True: + # 从摄像头读取一帧 ret, frame = cap.read() if not ret: print("Warning: Failed to read frame from camera") break - + current_time = time.time() + + # 使用检测引擎对当前帧进行推理,返回带标注的图像和原始结果 annotated_frame, results = self.engine.detect(frame) - + + # 安全检查:确保返回的图像有效 if annotated_frame is None or annotated_frame.size == 0: print("Warning: Invalid detection result") continue - + + # 显示带检测框的图像 cv2.imshow(self.window_name, annotated_frame) - + + # 检查键盘输入(等待 1 毫秒) key = cv2.waitKey(1) & 0xFF - if key == ord('q'): + if key == ord('q'): # 按 'q' 退出 break - elif key == ord('s'): + elif key == ord('s'): # 按 's' 保存当前帧 self.save_frame(annotated_frame) - + + # 更新 FPS 统计并按需打印 self._print_fps_if_needed(current_time) self.frame_count += 1 - + except KeyboardInterrupt: print("\nDetection interrupted by user.") except Exception as e: print(f"Unexpected error during detection: {e}") - traceback.print_exc() + traceback.print_exc() # 打印完整错误栈,便于调试 finally: + # 确保资源被正确释放 cap.release() cv2.destroyAllWindows() print("Camera released and windows closed.") - + def _print_fps_if_needed(self, current_time): + """ + 根据设定的时间间隔计算并打印当前 FPS(帧率)。 + + 参数: + 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}") + + # 重置计时器和帧计数器 self.last_output_time = current_time self.frame_count = 0 - + def save_frame(self, frame): - import os - timestamp = int(time.time()) + """ + 将当前帧保存为 JPEG 图像文件,文件名包含时间戳。 + + 参数: + frame (np.ndarray): 要保存的图像数组(BGR 格式) + """ + import os # 延迟导入(仅在此方法中使用) + timestamp = int(time.time()) # 使用 Unix 时间戳确保文件名唯一 filename = f"saved_frame_{timestamp}.jpg" success = cv2.imwrite(filename, frame) if success: From 5acf1346e98a2233d3a5e44be21f7a9f19f2af1c Mon Sep 17 00:00:00 2001 From: is-leplus <3210209742@qq.com> Date: Thu, 18 Dec 2025 15:52:33 +0800 Subject: [PATCH 4/5] Update detection_engine.py --- .../detection_engine.py | 76 ++++++++++++++++--- 1 file changed, 64 insertions(+), 12 deletions(-) diff --git a/src/image_object_detection/detection_engine.py b/src/image_object_detection/detection_engine.py index 7e68491ece..8c0d881b7a 100644 --- a/src/image_object_detection/detection_engine.py +++ b/src/image_object_detection/detection_engine.py @@ -1,46 +1,98 @@ # detection_engine.py +# 功能:封装 YOLOv8 模型的加载与推理逻辑,提供干净的检测接口 + from ultralytics import YOLO import io import sys + class DetectionEngine: + """ + 目标检测引擎类。 + 负责加载 YOLO 模型并对输入图像帧执行推理, + 同时屏蔽模型内部的冗余打印输出(如进度条、日志等), + 使主程序输出更整洁。 + """ + def __init__(self, model_path="yolov8n.pt", conf_threshold=0.25): + """ + 初始化检测引擎。 + + 参数: + model_path (str): YOLO 模型文件路径或名称(如 'yolov8n.pt') + conf_threshold (float): 置信度阈值,低于此值的检测结果将被过滤 + """ self.model_path = model_path self.conf_threshold = conf_threshold + # 加载 YOLO 模型(在初始化时完成,避免每次检测重复加载) self.model = self._load_model() - + def _load_model(self): - """加载YOLO模型并抑制输出""" + """ + 私有方法:加载 YOLO 模型,并抑制其标准输出和错误输出。 + + 原因:YOLO 在加载模型或首次推理时会自动打印信息(如设备、尺寸等), + 这些信息在 GUI 或自动化脚本中属于干扰。通过临时重定向 stdout/stderr 来静默加载。 + + 返回: + YOLO: 已加载的模型实例 + """ + # 保存原始的标准输出和错误流 old_stdout = sys.stdout old_stderr = sys.stderr + + # 临时重定向到 StringIO 缓冲区(丢弃所有输出) sys.stdout = io.StringIO() sys.stderr = io.StringIO() - + try: + # 加载模型(若为官方模型且未下载,会自动联网下载) + print(f"尝试加载模型: {self.model_path}") # 打印调试信息 model = YOLO(self.model_path) + except Exception as e: + print(f"加载模型失败: {e}") # 打印异常信息 + raise e # 重新抛出异常以便进一步处理 finally: + # 确保无论是否出错,都恢复原始输出流 sys.stdout = old_stdout sys.stderr = old_stderr - + return model - + def detect(self, frame): """ - 对输入帧进行检测。 - 返回: (annotated_frame: np.ndarray, results: List[Results]) - 即使无检测框,annotated_frame 也是原始图像(HWC格式)。 + 对单帧图像执行目标检测。 + + 参数: + frame (np.ndarray): 输入图像,格式为 HWC(高度, 宽度, 通道),BGR 或 RGB 均可(YOLO 内部会处理) + + 返回: + tuple: + - annotated_frame (np.ndarray): 带有检测框、标签和置信度的可视化图像(HWC, BGR 格式) + - results (List[ultralytics.engine.results.Results]): 原始检测结果对象列表(通常长度为1) + + 注意: + - 即使没有检测到任何目标,YOLO 仍会返回一个 Results 对象; + - annotated_frame 始终是有效图像(无检测时即为原图)。 """ + # 保存原始输出流 old_stdout = sys.stdout old_stderr = sys.stderr + + # 临时静音 YOLO 的 verbose 输出(如 "image 1/1 ...") sys.stdout = io.StringIO() sys.stderr = io.StringIO() - + try: + # 执行推理:传入图像、置信度阈值,并关闭详细日志(verbose=False) results = self.model(frame, conf=self.conf_threshold, verbose=False) finally: + # 恢复标准输出 sys.stdout = old_stdout sys.stderr = old_stderr - - # YOLOv8 always returns at least one result - annotated_frame = results[0].plot() # numpy array (H, W, C) + + # 使用 YOLO 内置的 plot() 方法生成带标注的图像(numpy array, HWC) + annotated_frame = results[0].plot() # results 总是包含至少一个元素 + return annotated_frame, results + From a84c4b3df3771f63da1adb8d064a7fd336e364b3 Mon Sep 17 00:00:00 2001 From: is-leplus <3210209742@qq.com> Date: Thu, 18 Dec 2025 15:53:05 +0800 Subject: [PATCH 5/5] Update image_detector.py --- src/image_object_detection/image_detector.py | 143 +++++++++++-------- 1 file changed, 82 insertions(+), 61 deletions(-) diff --git a/src/image_object_detection/image_detector.py b/src/image_object_detection/image_detector.py index 70f31256b2..03ba5c75c1 100644 --- a/src/image_object_detection/image_detector.py +++ b/src/image_object_detection/image_detector.py @@ -1,66 +1,87 @@ # image_detector.py -import cv2 +# 功能:封装 YOLOv8 模型的加载与推理逻辑,提供干净的检测接口 + +from ultralytics import YOLO +import io +import sys import numpy as np -import traceback -import os + class ImageDetector: - def __init__(self, detection_engine): - self.engine = detection_engine - - def detect_static_image(self, image_path): - print(f"Loading image: {image_path}") - - if not os.path.exists(image_path): - print(f"Error: Image file not found - {image_path}") - return - - frame = cv2.imread(image_path) - if frame is None or frame.size == 0: - print("Error: Failed to load image") - return - - print("Running detection...") - annotated_frame, results = self.engine.detect(frame) - - if annotated_frame is None or annotated_frame.size == 0: - print("Error: Invalid annotated frame") - return - - self._display_results(results) - self._show_image(annotated_frame, "YOLO_Static_Detection") - - def _display_results(self, results): - if not results: - print("No objects detected.") - return - - result = results[0] - boxes = result.boxes - if len(boxes) == 0: - print("No objects detected.") - return - - print(f"Detected {len(boxes)} object(s):") - names_list = self.engine.model.names - - for i, box in enumerate(boxes): - try: - cls_index = int(box.cls.item()) - confidence = box.conf.item() - cls_name = names_list[cls_index] if 0 <= cls_index < len(names_list) else f"unknown_{cls_index}" - print(f" {i+1}. {cls_name} (confidence: {confidence:.2f})") - except Exception as e: - print(f" Warning: Failed to parse box {i+1}: {e}") - - def _show_image(self, annotated_frame, window_name="YOLO_Static_Detection"): + """ + 目标检测引擎类。 + 负责加载 YOLO 模型并对输入图像帧执行推理, + 同时屏蔽模型内部的冗余打印输出(如进度条、日志等), + 使主程序输出更整洁。 + """ + + def __init__(self, model_path="yolov8n.pt", conf_threshold=0.25): + """ + 初始化检测引擎。 + + 参数: + model_path (str): YOLO 模型文件路径或名称(如 'yolov8n.pt') + conf_threshold (float): 置信度阈值,低于此值的检测结果将被过滤 + """ + self.model_path = model_path + self.conf_threshold = conf_threshold + # 加载 YOLO 模型(在初始化时完成,避免每次检测重复加载) + self.model = self._load_model() + + def _load_model(self): + """ + 私有方法:加载 YOLO 模型,并抑制其标准输出和错误输出。 + 原因:YOLO 在加载模型或首次推理时会自动打印信息(如设备、尺寸等), + 这些信息在 GUI 或自动化脚本中属于干扰。通过临时重定向 stdout/stderr 来静默加载。 + + 返回: + YOLO: 已加载的模型实例 + """ + # 保存原始的标准输出和错误流 + old_stdout = sys.stdout + old_stderr = sys.stderr + # 临时重定向到 StringIO 缓冲区(丢弃所有输出) + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() try: - cv2.destroyAllWindows() - cv2.namedWindow(window_name, cv2.WINDOW_NORMAL) - cv2.resizeWindow(window_name, 800, 600) - cv2.imshow(window_name, annotated_frame) - cv2.waitKey(0) - cv2.destroyAllWindows() - except Exception as e: - print(f"Failed to display image: {e}") - traceback.print_exc() + # 加载模型(若为官方模型且未下载,会自动联网下载) + model = YOLO(self.model_path) + finally: + # 确保无论是否出错,都恢复原始输出流 + sys.stdout = old_stdout + sys.stderr = old_stderr + return model + + def detect(self, frame: np.ndarray): + """ + 对单帧图像执行目标检测。 + + 参数: + frame (np.ndarray): 输入图像,格式为 HWC(高度, 宽度, 通道),BGR 或 RGB 均可(YOLO 内部会处理) + + 返回: + tuple: + - annotated_frame (np.ndarray): 带有检测框、标签和置信度的可视化图像(HWC, BGR 格式) + - results (List[ultralytics.engine.results.Results]): 原始检测结果对象列表(通常长度为1) + + 注意: + - 即使没有检测到任何目标,YOLO 仍会返回一个 Results 对象; + - annotated_frame 始终是有效图像(无检测时即为原图)。 + """ + # 保存原始输出流 + old_stdout = sys.stdout + old_stderr = sys.stderr + # 临时静音 YOLO 的 verbose 输出(如 "image 1/1 ...") + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + try: + # 执行推理:传入图像、置信度阈值,并关闭详细日志(verbose=False) + results = self.model(frame, conf=self.conf_threshold, verbose=False) + finally: + # 恢复标准输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 使用 YOLO 内置的 plot() 方法生成带标注的图像(numpy array, HWC) + annotated_frame = results[0].plot() # results 总是包含至少一个元素 + return annotated_frame, results