计算机视觉 / 系统课时
运行首个检测示例
运行首个检测示例
本课使用 yolov8n.pt 对示例图像执行一次完整检测,并把标注结果保存到固定目录。完成后,你将能够确认模型权重、输入图像、推理代码和输出文件是否形成了可运行闭环。
学习目标
- 使用预训练权重执行单张图像检测
- 读取检测数量并定位标注结果文件
- 根据输出目录和异常信息判断运行是否成功
准备首个示例
在项目根目录创建 src/first_detect.py。脚本首次运行时会下载示例图像和 yolov8n.pt;已经存在的文件会被直接复用,因此再次运行不会重复下载示例图像。
python
from pathlib import Path
from urllib.request import urlretrieve
from ultralytics import YOLO
image_dir = Path("data/images")
image_dir.mkdir(parents=True, exist_ok=True)
image_path = image_dir / "bus.jpg"
if not image_path.exists():
urlretrieve(
"https://ultralytics.com/images/bus.jpg",
image_path,
)
model = YOLO("yolov8n.pt")
results = model.predict(
source=str(image_path),
conf=0.25,
save=True,
project="runs/detect",
name="first",
exist_ok=True,
verbose=False,
)
result = results[0]
box_count = 0 if result.boxes is None else len(result.boxes)
output_path = Path("runs/detect/first") / image_path.name
print(f"检测完成:{box_count} 个目标")
print(f"标注图像:{output_path}")代码把置信度阈值设为 0.25,并通过 project 与 name 固定输出目录。exist_ok=True 允许重复运行时复用 runs/detect/first,避免自动生成 first2、first3 等目录。
执行检测
确认虚拟环境已激活,然后从项目根目录运行:
bash
python src/first_detect.py预期输出:
text
检测完成:<COUNT> 个目标
标注图像:runs/detect/first/bus.jpg<COUNT> 会受到权重版本、运行环境和推理实现影响,首次运行还可能出现权重或图片下载进度。只要程序正常结束,并生成指定图像,就表示推理链路已经工作。
查看结果与日志
打开 runs/detect/first/bus.jpg,应看到原图上的目标框、类别名称和置信度。输出图像用于快速检查模型是否识别到合理对象;程序打印的目标数量则适合后续接入统计、接口响应或批量处理。
如果输出目录不存在,先检查脚本是否从项目根目录运行;如果出现 ModuleNotFoundError,检查开发工具绑定的解释器;如果权重或图片下载失败,检查网络后重试,也可以把对应文件手动放到脚本约定的位置。
按自己的节奏,确认真正理解。