Skip to content
Merged
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
92 changes: 70 additions & 22 deletions src/image_object_detection/camera_detector.py
Original file line number Diff line number Diff line change
@@ -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:
Expand Down
34 changes: 31 additions & 3 deletions src/image_object_detection/config.py
Original file line number Diff line number Diff line change
@@ -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

76 changes: 64 additions & 12 deletions src/image_object_detection/detection_engine.py
Original file line number Diff line number Diff line change
@@ -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

Loading
Loading