Skip to content
Merged
51 changes: 45 additions & 6 deletions src/image_object_detection/batch_detector.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
# batch_detector.py
"""
批量图像检测器模块。

该模块提供一个 BatchDetector 类,用于对指定输入目录中的所有图像文件
进行批量目标检测,并将带有检测结果(如边界框、标签等)的图像保存到输出目录。
"""

import os
import cv2
Expand All @@ -7,51 +13,84 @@


class BatchDetector:
"""
批量图像检测器类。

使用提供的 DetectionEngine 对象,对输入目录中的图像逐一进行目标检测,
并将标注后的图像保存至输出目录。
"""

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)
"""
初始化 BatchDetector 实例。

参数:
detection_engine (DetectionEngine): 已加载模型的检测引擎实例。
input_dir (str 或 Path): 包含待检测图像的输入目录路径。
output_dir (str 或 Path): 用于保存检测结果图像的输出目录路径。
"""
self.engine = detection_engine # 检测引擎实例
self.input_dir = Path(input_dir) # 输入目录(转换为 Path 对象)
self.output_dir = Path(output_dir) # 输出目录(转换为 Path 对象)

# 支持的图像文件扩展名集合(小写)
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
success_count = 0 # 成功处理的图像计数器

# 按文件名排序以保证处理顺序可预测
for img_path in sorted(image_files):
try:
# 读取图像
# 使用 OpenCV 读取图像
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(带标注的图像),_(检测结果元数据,此处未使用)
annotated_frame, _ = self.engine.detect(frame)

# 构造输出文件路径:保留原文件名,在扩展名前加 "_detected"
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.")
62 changes: 40 additions & 22 deletions src/image_object_detection/config.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
# config.py
# 功能:定义项目全局配置参数,便于统一管理和修改
# 支持从外部 config.yaml 文件加载配置;若文件不存在,则使用内置默认值。

import os
import yaml
from pathlib import Path

class ConfigError(Exception):
"""配置相关异常的基类"""
Expand All @@ -12,42 +15,57 @@ class Config:
应用程序的配置类。
所有核心参数(如模型路径、默认图像路径、阈值等)集中在此初始化,
便于维护和部署时调整。

配置优先级(从高到低):
1. 外部 config.yaml 文件(位于项目根目录)
2. 内置默认值(硬编码在本类中)
"""
def __init__(self):
def __init__(self, config_file="config.yaml"):
# 获取当前 config.py 文件所在目录的绝对路径
# 使用 os.path.abspath 确保路径在不同操作系统下一致
base_dir = os.path.dirname(os.path.abspath(__file__))
base_dir = Path(os.path.dirname(os.path.abspath(__file__)))

# 默认测试图像路径:位于项目根目录下的 data/test.jpg
# 若用户未指定图像路径,系统将尝试加载此文件
self.default_image_path = os.path.join(base_dir, "data", "test.jpg")
# 构建配置文件的完整路径(相对于项目根目录)
config_path = base_dir / config_file

# YOLO 模型权重文件路径
# 支持:
# - 内置模型名(如 "yolov8n.pt",首次运行会自动下载)
# - 自定义训练模型的相对或绝对路径(如 "runs/detect/train/weights/best.pt")
self.model_path = "yolov8n.pt"
# 内置默认配置(与原逻辑一致)
default_config = {
"default_image_path": str(base_dir / "data" / "test.jpg"),
"model_path": "yolov8n.pt",
"confidence_threshold": 0.25,
"camera_index": 0,
"output_interval": 1.0,
}

# 目标检测的置信度阈值
# 只有置信度 ≥ 此值的检测框才会被保留和显示
# 范围:0.0 ~ 1.0,值越高,结果越严格
self.confidence_threshold = 0.25
# 尝试从外部 YAML 文件加载用户配置
if config_path.is_file():
try:
with open(config_path, 'r', encoding='utf-8') as f:
user_config = yaml.safe_load(f) or {}
# 合并:用户配置覆盖默认值
default_config.update(user_config)
except yaml.YAMLError as e:
raise ConfigError(f"Invalid YAML syntax in {config_file}: {e}")
except Exception as e:
raise ConfigError(f"Failed to read {config_file}: {e}")

# 摄像头设备索引
# 通常 0 表示内置摄像头,外接摄像头可能为 1、2 等
self.camera_index = 0

# FPS(帧率)输出的时间间隔(单位:秒)
# 例如设为 1.0 表示每秒打印一次当前处理速度
self.output_interval = 1.0
# 提取配置项(保持与原字段名一致)
self.default_image_path = default_config["default_image_path"]
self.model_path = default_config["model_path"]
self.confidence_threshold = float(default_config["confidence_threshold"])
self.camera_index = int(default_config["camera_index"])
self.output_interval = float(default_config["output_interval"])

# 路径标准化:若 default_image_path 是相对路径,则基于项目根目录解析
if not os.path.isabs(self.default_image_path):
self.default_image_path = str(base_dir / self.default_image_path)

# 验证置信度阈值
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:
if self.camera_index < 0:
raise ConfigError("camera_index must be a non-negative integer")

# 验证输出间隔
Expand Down
9 changes: 9 additions & 0 deletions src/image_object_detection/config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# config.yaml
# YOLOv8 检测系统配置文件
# 所有字段均为可选项;未指定时将使用内置默认值

model_path: "yolov8n.pt"
confidence_threshold: 0.3
camera_index: 0
output_interval: 1.0
default_image_path: "data/test.jpg"
Loading