
本文详解如何正确解析yolo格式(归一化中心坐标+宽高)的文本标注文件,并转换为像素级坐标,实现图像中目标区域的精准裁剪,避免常见坐标误用导致的裁剪偏移或截断。
本文详解如何正确解析yolo格式(归一化中心坐标+宽高)的文本标注文件,并转换为像素级坐标,实现图像中目标区域的精准裁剪,避免常见坐标误用导致的裁剪偏移或截断。
在计算机视觉任务中,尤其是目标检测后的结果可视化或数据增强阶段,常需依据标注文件对原始图像进行目标区域裁剪。但实践中,大量开发者因混淆标注格式(如YOLO vs. Pascal VOC)而出现裁剪错位——例如将归一化的中心点坐标(x_center, y_center)和宽高(w, h) 误当作左上角坐标使用,导致裁剪框严重偏离实际目标(如车牌、头盔等小目标被部分截断甚至完全丢失)。
您提供的代码逻辑整体合理,但存在一个关键性偏差:虽已识别出YOLO格式的5元组(class x_c y_c w h),却在坐标转换时未严格遵循YOLO定义的归一化规则与像素映射关系。具体问题在于:
- YOLO标注中 x_center, y_center, width, height 均为相对于图像宽高的归一化值(范围 [0,1]);
- 转换为像素坐标时,必须先乘以对应图像尺寸,再通过 x1 = x_center - w/2、x2 = x_center + w/2 等方式计算真实边界;
- 原始代码中 half_width = int(width * img_width / 2) 的计算是正确的,但后续 x1 = max(0, x_center - half_width) 使用的是已转为整数的 x_center(即 int(x_center * img_width)),而该值本身已是像素坐标,不应再参与“减半宽”的运算逻辑——这会导致数值精度损失与边界偏移。
✅ 正确做法是:全程在浮点精度下完成坐标计算,最后统一取整并做边界裁剪。以下是修正后的核心逻辑(含完整可运行示例):
import os
import cv2
def crop_image_with_annotation(image_path, annotation_path, output_folder):
img = cv2.imread(image_path)
if img is None:
print(f"[ERROR] Failed to load image: {image_path}")
return
h, w = img.shape[:2] # 注意:cv2.imread 返回 (height, width, channels)
try:
with open(annotation_path, 'r') as f:
for line_num, line in enumerate(f, 1):
line = line.strip()
if not line:
continue
values = line.split()
# 支持单目标(4值)或带类别(5值)的YOLO格式
if len(values) == 5:
_, x_c_norm, y_c_norm, w_norm, h_norm = map(float, values)
elif len(values) == 4:
x_c_norm, y_c_norm, w_norm, h_norm = map(float, values)
else:
print(f"[WARN] Invalid line {line_num} in {annotation_path}: {line}")
continue
# ✅ 关键修正:浮点精度下计算像素坐标(避免int中间截断)
x_center = x_c_norm * w
y_center = y_c_norm * h
box_w = w_norm * w
box_h = h_norm * h
x1 = max(0, int(x_center - box_w / 2))
y1 = max(0, int(y_center - box_h / 2))
x2 = min(w, int(x_center + box_w / 2))
y2 = min(h, int(y_center + box_h / 2))
if x1 >= x2 or y1 >= y2:
print(f"[WARN] Invalid bbox at line {line_num} in {annotation_path}: ({x1},{y1})→({x2},{y2})")
continue
cropped = img[y1:y2, x1:x2]
base_name = os.path.splitext(os.path.basename(image_path))[0]
out_name = f"{base_name}_crop_{line_num}.jpg"
out_path = os.path.join(output_folder, out_name)
cv2.imwrite(out_path, cropped)
print(f"[OK] Cropped → {out_path} | bbox: ({x1},{y1}), ({x2},{y2})")
except Exception as e:
print(f"[ERROR] Failed to process annotation {annotation_path}: {e}")
# --- 批量处理主流程 ---
input_folder = r"C:\Users\Desktop\crop"
output_folder = r"C:\Users\Desktop\crop\new"
os.makedirs(output_folder, exist_ok=True)
for fname in os.listdir(input_folder):
if fname.lower().endswith(('.jpg', '.jpeg', '.png')):
img_path = os.path.join(input_folder, fname)
txt_path = os.path.join(input_folder, os.path.splitext(fname)[0] + ".txt")
if os.path.exists(txt_path):
crop_image_with_annotation(img_path, txt_path, output_folder)
else:
print(f"[SKIP] Missing annotation for {fname}")
? 关键改进说明:
- 精度保障:所有归一化坐标先转为浮点像素值,再执行 ±w/2 运算,最后 int() 取整,避免因过早取整引入累积误差;
- 多目标支持:自动遍历 .txt 中每一行(对应一个检测框),为每张图生成多个裁剪结果(如您的示例含4个头盔/车牌框);
- 鲁棒性增强:增加空行跳过、无效框过滤(x1>=x2)、异常捕获等防御性逻辑;
- 输出可追溯:裁剪文件名包含序号(_crop_1.jpg),便于与标注行一一对应调试。
⚠️ 注意事项:
- YOLO格式要求图像宽高为正整数,且标注值必须在 [0,1] 区间内;若出现负值或超限值,需检查标注工具导出设置;
- OpenCV 默认通道顺序为 BGR,如需RGB输出,可在保存前加 cv2.cvtColor(cropped, cv2.COLOR_BGR2RGB);
- 若需保留原始比例(如车牌OCR),建议裁剪后添加 padding 或 resize 到固定尺寸,而非直接拉伸。
通过以上修正,您的脚本将能稳定、准确地从YOLO标注中提取任意数量的目标区域(包括车牌、头盔、车辆等),为后续识别、分类或数据集构建提供高质量裁剪样本。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!











