Learn how anchor boxes act as templates for object detection. Explore their role in localization, compare anchor-based vs. anchor-free models like [YOLO26](https://docs.ultralytics.com/models/yolo26/), and discover real-world CV applications.
锚点框是预先定义的参考矩形,具有特定的宽高比和比例,分布在图像各处以协助目标检测模型定位和分类物体。相较于要求神经网络从零开始预测物体的精确尺寸和位置——这种方法因物体形状的多样性可能导致结果不稳定——该模型将这些固定模板作为起点。 通过学习如何调整(即"回归")这些初始框以匹配实际目标,系统能实现更快的收敛速度和更高的准确率。该技术将复杂的定位任务简化为更易处理的优化问题,从而从根本上革新了计算机视觉(CV)领域。
在经典锚点检测器中,输入图像会被划分为网格单元。在每个单元位置,网络会生成多个几何形状各异的锚点框。例如,为同时detect 高detect 人与宽体汽车,模型可能在同一中心点处生成一个高而窄的框和一个矮而宽的框。
During model training, these anchors are matched against actual objects using a metric called Intersection over Union (IoU). Anchors that overlap significantly with a labeled object are designated as "positive" samples. The network then learns two parallel tasks:
该方法使模型能够处理多个尺寸不同且彼此邻近的物体,因为每个物体 都可以被分配到最符合其形状的锚点上。
尽管新型架构正朝着无锚点设计方向发展,但在许多成熟的生产系统中,锚点框依然至关重要——这些系统中物体的特征具有可预测性。
区分传统的锚点法与现代无锚点检测器至关重要。
虽然现代高级API(Ultralytics )在训练过程中会抽象掉这些细节,但理解锚点在处理旧版模型架构或分析模型配置文件时仍很有用。以下代码片段演示了如何加载模型并检查其配置,其中锚点设置(若存在)通常在此处定义。
from ultralytics import YOLO
# Load a pre-trained YOLO model (YOLO26 is anchor-free, but legacy configs act similarly)
model = YOLO("yolo26n.pt")
# Inspect the model's stride, which relates to grid cell sizing in detection
print(f"Model strides: {model.model.stride}")
# For older anchor-based models, anchors might be stored in the model's attributes
# Modern anchor-free models calculate targets dynamically without fixed boxes
if hasattr(model.model, "anchors"):
print(f"Anchors: {model.model.anchors}")
else:
print("This model architecture is anchor-free.")
尽管锚框技术效果显著,但其引入了复杂性。海量锚框(每张图像常达数万个)导致类别失衡问题,因多数锚框仅覆盖背景。 为缓解此问题,采用焦点损失等技术通过降低易识别背景样本的权重进行补偿。此外,最终输出通常需要非最大抑制(NMS)过滤冗余重叠框,确保每个目标仅保留最可靠的检测结果。