计算机视觉 / 系统课时
封装 Python 推理模块
封装 Python 推理模块
本课把 YOLOv5 的模型加载、图片解码、推理执行和结果转换收拢到一个可复用类中。完成后,接口层只需传入图片路径和阈值,就能获得结构化结果,同时避免每次请求重复加载权重。
学习目标
- 划分模型生命周期、输入预处理和结果转换的职责
- 编写可复用的
YoloV5Detector推理类 - 通过命令行验证结构化检测结果
明确模块职责与生命周期
推理模块应在进程启动时加载一次模型,在每次请求中只处理图片和执行推理。若把 torch.hub.load() 放进接口函数,每个请求都会重新读取权重,延迟和显存占用都会显著增加。

本模块把职责分成三层:构造函数负责路径检查和模型加载,私有方法负责图片解码与类别名转换,predict() 负责一次完整推理。接口层不直接操作张量,也不依赖 YOLOv5 的内部结果对象。
实现可复用检测器
以下代码依赖本地 YOLOv5 仓库、训练权重和 Pillow。torch.hub.load(..., source="local") 会使用仓库中的 hubconf.py 创建模型,默认 AutoShape 包装会继续处理缩放、填充和归一化。
from __future__ import annotations
import argparse
import json
from dataclasses import asdict, dataclass
from pathlib import Path
from time import perf_counter
from typing import Any
import torch
from PIL import Image, ImageOps
@dataclass(frozen=True)
class Detection:
label: str
class_id: int
confidence: float
x1: float
y1: float
x2: float
y2: float
@dataclass(frozen=True)
class DetectionResult:
width: int
height: int
elapsed_ms: float
detections: list[Detection]
def to_dict(self) -> dict[str, Any]:
return {
"width": self.width,
"height": self.height,
"elapsedMs": self.elapsed_ms,
"objectCount": len(self.detections),
"detections": [asdict(item) for item in self.detections],
}
class YoloV5Detector:
def __init__(
self,
repo_dir: str,
weights_path: str,
device: str | None = None,
image_size: int = 640,
) -> None:
repo = Path(repo_dir).resolve()
weights = Path(weights_path).resolve()
if not (repo / "hubconf.py").is_file():
raise FileNotFoundError(f"invalid YOLOv5 repo: {repo}")
if not weights.is_file():
raise FileNotFoundError(f"weights not found: {weights}")
self.device = device or ("cuda:0" if torch.cuda.is_available() else "cpu")
self.image_size = image_size
# 权重只在实例创建时加载一次,后续请求复用同一模型。
self.model = torch.hub.load(
str(repo),
"custom",
path=str(weights),
source="local",
force_reload=False,
)
self.model.to(self.device).eval()
self.names = self.model.names
@staticmethod
def _load_image(image_path: str) -> Image.Image:
path = Path(image_path)
if not path.is_file():
raise FileNotFoundError(f"image not found: {path}")
with Image.open(path) as source:
# 先修正手机照片的 EXIF 方向,再统一为 RGB。
return ImageOps.exif_transpose(source).convert("RGB").copy()
def _class_name(self, class_id: int) -> str:
if isinstance(self.names, dict):
return str(self.names[class_id])
return str(self.names[class_id])
def predict(
self,
image_path: str,
conf: float = 0.25,
iou: float = 0.45,
) -> DetectionResult:
if not 0 <= conf <= 1 or not 0 <= iou <= 1:
raise ValueError("conf and iou must be between 0 and 1")
image = self._load_image(image_path)
self.model.conf = conf
self.model.iou = iou
started = perf_counter()
with torch.inference_mode():
results = self.model(image, size=self.image_size)
elapsed_ms = round((perf_counter() - started) * 1000, 2)
detections: list[Detection] = []
for x1, y1, x2, y2, score, class_id in results.xyxy[0].cpu().tolist():
cls = int(class_id)
detections.append(
Detection(
label=self._class_name(cls),
class_id=cls,
confidence=round(float(score), 6),
x1=round(float(x1), 2),
y1=round(float(y1), 2),
x2=round(float(x2), 2),
y2=round(float(y2), 2),
)
)
width, height = image.size
return DetectionResult(width, height, elapsed_ms, detections)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--repo", required=True)
parser.add_argument("--weights", required=True)
parser.add_argument("--image", required=True)
parser.add_argument("--device", default=None)
parser.add_argument("--conf", type=float, default=0.25)
parser.add_argument("--iou", type=float, default=0.45)
args = parser.parse_args()
detector = YoloV5Detector(args.repo, args.weights, args.device)
result = detector.predict(args.image, args.conf, args.iou)
print(json.dumps(result.to_dict(), ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()这段代码假设文件保存为 detector.py。本地 YOLOv5 仓库中必须存在 hubconf.py,权重文件可以是训练得到的 best.pt。首次运行时若环境缺少仓库依赖,应先在 YOLOv5 目录执行 python -m pip install -r requirements.txt。
运行并验证结果
执行以下命令,路径按实际目录调整:
python detector.py --repo ./yolov5 --weights ./weights/best.pt --image ./samples/test.jpg --conf 0.25 --iou 0.45预期结果是一段合法 JSON。下面数值仅展示结构,类别、坐标、耗时和数量会随权重、图片与设备变化:
{
"width": 1280,
"height": 720,
"elapsedMs": 18.73,
"objectCount": 1,
"detections": [
{
"label": "person",
"class_id": 0,
"confidence": 0.913245,
"x1": 214.36,
"y1": 88.42,
"x2": 612.18,
"y2": 701.55
}
]
}若仓库路径错误,程序会抛出 invalid YOLOv5 repo;若权重或图片不存在,会在加载模型或读取图片前明确失败。这样可以把路径问题与模型推理异常区分开。
处理关键边界
conf 决定低置信度候选是否保留,iou 影响 NMS 对重叠框的抑制强度,两者都必须限制在 0~1。接口层可以提前校验,但推理模块仍要保留自己的防御性检查,避免被命令行、定时任务或其他调用方绕过。
当前实现直接修改模型实例的 conf 和 iou。单线程服务没有问题;若多个请求并发共享同一实例,不同请求可能互相覆盖阈值。生产环境可在接口层使用锁串行修改与推理,或为固定阈值创建独立实例。
GPU 首次推理通常包含 CUDA 初始化和算子预热,耗时会高于后续请求。部署时可在服务启动后用一张测试图执行一次预热,但预热失败应阻止服务进入就绪状态,避免把问题推迟到第一个真实请求。
接入接口层
接入上一课的 FastAPI 接口时,应在应用启动阶段创建一个 YoloV5Detector 实例,并在请求处理函数中调用 predict()。接口层只负责把 DetectionResult 转换为对外字段,例如把 class_id 映射为 classId,模型路径、设备选择和张量结构继续留在模块内部。
验收时至少确认三点:连续调用不会重复加载模型;同一图片和同一阈值得到稳定结构;无目标图片返回空 detections,而不是 null 或异常。
本课总结
- 模型应在进程级生命周期中加载一次,请求阶段只执行图片处理和推理
- 推理模块要返回普通数据结构,避免把 YOLOv5 内部对象泄露给接口层
- 路径、阈值、并发修改和首次 GPU 预热是部署前必须验证的边界
下一课预告
下一课将把推理模块接入检测接口,并处理异步上传、线程阻塞、模型预热和服务就绪检查。