From e9de52383a1ad26ae30b2b222012e4b0e131ffd7 Mon Sep 17 00:00:00 2001 From: is-leplus <3210209742@qq.com> Date: Wed, 17 Dec 2025 20:57:52 +0800 Subject: [PATCH 1/5] Update image_detector.py --- src/image_object_detection/image_detector.py | 90 +++++++++++++++----- 1 file changed, 70 insertions(+), 20 deletions(-) diff --git a/src/image_object_detection/image_detector.py b/src/image_object_detection/image_detector.py index 70f31256b2..0bd279bb1d 100644 --- a/src/image_object_detection/image_detector.py +++ b/src/image_object_detection/image_detector.py @@ -1,66 +1,116 @@ # image_detector.py +# 功能:对单张静态图像执行目标检测,并可视化结果 + import cv2 import numpy as np import traceback import os + class ImageDetector: + """ + 静态图像检测器类。 + 接收一个检测引擎(如 YOLO 模型封装),加载指定路径的图像, + 执行目标检测,并在窗口中显示带标注的结果,同时打印检测信息到控制台。 + """ + def __init__(self, detection_engine): + """ + 初始化图像检测器。 + + 参数: + detection_engine: 实现 detect(frame) 方法的对象(如 DetectionEngine 实例) + """ self.engine = detection_engine - + def detect_static_image(self, image_path): + """ + 对指定路径的静态图像执行目标检测。 + + 参数: + image_path (str): 待检测图像的文件路径 + """ print(f"Loading image: {image_path}") - + + # 检查图像文件是否存在 if not os.path.exists(image_path): print(f"Error: Image file not found - {image_path}") return - + + # 使用 OpenCV 读取图像(BGR 格式) 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): + """ + 私有方法:解析并打印检测结果到控制台。 + + 参数: + results (List[Results]): YOLO 返回的检测结果列表(通常长度为1) + """ + # 若结果为空或无检测框,提示用户 if not results: print("No objects detected.") return - - result = results[0] + + result = results[0] # YOLO 总是返回至少一个 Results 对象 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 - + names_list = self.engine.model.names # 获取模型的类别名称列表 + + # 遍历每个检测框,提取类别索引、置信度和类别名 for i, box in enumerate(boxes): try: - cls_index = int(box.cls.item()) - confidence = box.conf.item() + cls_index = int(box.cls.item()) # 类别索引(tensor → int) + confidence = box.conf.item() # 置信度(tensor → float) + # 安全获取类别名称,防止索引越界 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})") + print(f" {i+1}. {cls_name} (confidence: {confidence:.2f})") except Exception as e: - print(f" Warning: Failed to parse box {i+1}: {e}") - + print(f" Warning: Failed to parse box {i+1}: {e}") + def _show_image(self, annotated_frame, window_name="YOLO_Static_Detection"): + """ + 私有方法:使用 OpenCV 显示带标注的图像。 + + 参数: + annotated_frame (np.ndarray): 带检测框的图像(HWC, BGR) + window_name (str): 显示窗口的标题 + """ try: + # 关闭可能已存在的同名窗口,避免残留 cv2.destroyAllWindows() + + # 创建可调整大小的窗口(便于查看大图) cv2.namedWindow(window_name, cv2.WINDOW_NORMAL) - cv2.resizeWindow(window_name, 800, 600) + cv2.resizeWindow(window_name, 800, 600) # 初始窗口大小 + + # 显示图像,并等待任意按键关闭 cv2.imshow(window_name, annotated_frame) - cv2.waitKey(0) + cv2.waitKey(0) # 0 表示无限等待,直到按键 cv2.destroyAllWindows() except Exception as e: print(f"Failed to display image: {e}") - traceback.print_exc() + traceback.print_exc() # 打印完整错误栈,便于调试 From 7b70366abe28eefcaaa4fb47cb5173a952170c98 Mon Sep 17 00:00:00 2001 From: is-leplus <3210209742@qq.com> Date: Wed, 17 Dec 2025 21:31:17 +0800 Subject: [PATCH 2/5] Update detection_engine.py --- .../detection_engine.py | 71 +++++++++++++++---- 1 file changed, 59 insertions(+), 12 deletions(-) diff --git a/src/image_object_detection/detection_engine.py b/src/image_object_detection/detection_engine.py index 7e68491ece..e9b6fc724a 100644 --- a/src/image_object_detection/detection_engine.py +++ b/src/image_object_detection/detection_engine.py @@ -1,46 +1,93 @@ # 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: + # 加载模型(若为官方模型且未下载,会自动联网下载) model = YOLO(self.model_path) 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 b82b98532367684d84cd33e659901813461dcef2 Mon Sep 17 00:00:00 2001 From: is-leplus <3210209742@qq.com> Date: Wed, 17 Dec 2025 21:49:47 +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 7ada28f50cc6d423f6eb564b06cd9d64340e20db Mon Sep 17 00:00:00 2001 From: is-leplus <3210209742@qq.com> Date: Thu, 18 Dec 2025 00:09:46 +0800 Subject: [PATCH 4/5] Update config.py --- src/image_object_detection/config.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/image_object_detection/config.py b/src/image_object_detection/config.py index c4b3d7f107..277510f4c5 100644 --- a/src/image_object_detection/config.py +++ b/src/image_object_detection/config.py @@ -18,7 +18,7 @@ def __init__(self): # 默认测试图像路径:位于项目根目录下的 data/test.jpg # 若用户未指定图像路径,系统将尝试加载此文件 - self.default_image_path = os.path.join(base_dir, "data", "test.jpg") + self.default_image_path = r"C:\Users\apple\OneDrive\桌面\test.jpg" # YOLO 模型权重文件路径 # 支持: @@ -38,3 +38,4 @@ def __init__(self): # FPS(帧率)输出的时间间隔(单位:秒) # 例如设为 1.0 表示每秒打印一次当前处理速度 self.output_interval = 1.0 + From 758b18a8f1d22ce97237ce892c3e66acb1bde8bd Mon Sep 17 00:00:00 2001 From: is-leplus <3210209742@qq.com> Date: Thu, 18 Dec 2025 00:19:30 +0800 Subject: [PATCH 5/5] Update ui_handler.py --- src/image_object_detection/ui_handler.py | 35 ++++++++++++++++++------ 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/src/image_object_detection/ui_handler.py b/src/image_object_detection/ui_handler.py index da8300ed41..de47f80899 100644 --- a/src/image_object_detection/ui_handler.py +++ b/src/image_object_detection/ui_handler.py @@ -5,8 +5,6 @@ import cv2 import argparse from detection_engine import DetectionEngine -from image_detector import ImageDetector -from camera_detector import CameraDetector def parse_args(): @@ -92,7 +90,7 @@ def _choose_image_source(self): 子菜单:让用户选择使用默认测试图像还是输入自定义路径。 默认路径硬编码为桌面的 test.jpg(适用于快速测试)。 """ - default_image_path = r"C:\Users\apple\OneDrive\桌面\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") @@ -111,6 +109,8 @@ def _choose_image_source(self): # 获取用户输入的路径,并展开 ~ 符号(如 ~/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 @@ -120,16 +120,34 @@ def _choose_image_source(self): 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) + + # 显示结果 + cv2.imshow("YOLO Detection Result", 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 @@ -141,6 +159,7 @@ def _run_camera_detection(self): 使用配置中的摄像头索引和输出间隔参数。 """ try: + from camera_detector import CameraDetector detector = CameraDetector( detection_engine=self.engine, output_interval=self.config.output_interval