
本文详解如何正确解析yolo格式(归一化中心坐标+宽高)的文本标注文件,并转换为像素级坐标,实现高精度图像裁剪,避免因坐标理解错误导致的裁剪偏移或截断。
本文详解如何正确解析yolo格式(归一化中心坐标+宽高)的文本标注文件,并转换为像素级坐标,实现高精度图像裁剪,避免因坐标理解错误导致的裁剪偏移或截断。
在计算机视觉任务中,尤其是目标检测后的后处理阶段,常需根据标注文件对原始图像进行单目标或多目标裁剪。但实践中,大量开发者因混淆标注格式而引入严重误差——典型案例如YOLO系列标注(.txt)采用归一化的中心点坐标(x_center, y_center)与归一化宽高(width, height),而非常见的左上-右下角坐标。若直接按“左上角”理解 x_center, y_center,将导致裁剪区域整体偏移,甚至完全丢失目标(如车牌、头盔等小目标)。
您提供的代码逻辑基本正确,但存在一个关键疏漏:未对多行标注做循环处理。您的示例标注文件包含4行(对应2辆摩托车及各自佩戴的2个头盔),而原代码仅读取首行(f.readline()),导致仅裁剪第一个目标(如车牌),其余目标被忽略。此外,坐标转换虽方向正确,但整型截断(int())和边界约束方式可进一步增强鲁棒性。
以下是修复并增强后的完整实现:
import os
import cv2
def crop_image_with_annotations(image_path, annotation_path, output_folder, suffix=""):
"""
基于YOLO格式标注文件批量裁剪图像中所有目标
Args:
image_path: 原图路径
annotation_path: 对应.txt标注路径(每行: class x_c y_c w h,归一化)
output_folder: 输出文件夹
suffix: 可选后缀(如'_0', '_1')用于区分同一图像的多个裁剪结果
"""
# 读取图像
img = cv2.imread(image_path)
if img is None:
print(f"[ERROR] 无法加载图像: {image_path}")
return
img_height, img_width = img.shape[:2]
# 读取全部标注行
crops = []
try:
with open(annotation_path, 'r') as f:
for line_idx, line in enumerate(f):
line = line.strip()
if not line:
continue
values = line.split()
# 支持带类别标签(5值)或无类别(4值)格式
if len(values) == 5:
_, x_c, y_c, w, h = map(float, values)
elif len(values) == 4:
x_c, y_c, w, h = map(float, values)
else:
print(f"[WARN] 第{line_idx+1}行格式异常({len(values)}项),跳过: {line}")
continue
# ✅ 归一化 → 像素坐标:中心点 + 宽高 → 左上/右下角
x1 = int((x_c - w / 2) * img_width)
y1 = int((y_c - h / 2) * img_height)
x2 = int((x_c + w / 2) * img_width)
y2 = int((y_c + h / 2) * img_height)
# ✅ 安全裁剪:强制约束在图像范围内(避免负值或越界)
x1, y1 = max(0, x1), max(0, y1)
x2, y2 = min(img_width, x2), min(img_height, y2)
if x2 <= x1 or y2 <= y1:
print(f"[WARN] 第{line_idx+1}个目标裁剪区域无效({x1},{y1}→{x2},{y2}),跳过")
continue
cropped = img[y1:y2, x1:x2]
crops.append((cropped, line_idx))
except FileNotFoundError:
print(f"[ERROR] 标注文件不存在: {annotation_path}")
return
except Exception as e:
print(f"[ERROR] 解析标注时异常: {e}")
return
# 保存所有裁剪结果
base_name = os.path.splitext(os.path.basename(image_path))[0]
for idx, (crop_img, line_idx) in enumerate(crops):
# 生成唯一文件名:原图名_序号.jpg
out_name = f"{base_name}_{line_idx}{suffix}.jpg"
out_path = os.path.join(output_folder, out_name)
cv2.imwrite(out_path, crop_img)
print(f"✓ 裁剪保存: {out_path} ({crop_img.shape[1]}×{crop_img.shape[0]})")
# --- 主执行流程 ---
input_folder = r"C:\Users\Desktop\crop"
output_folder = r"C:\Users\Desktop\crop\new"
os.makedirs(output_folder, exist_ok=True)
for filename in os.listdir(input_folder):
if not filename.lower().endswith(('.jpg', '.jpeg', '.png')):
continue
image_path = os.path.join(input_folder, filename)
txt_name = os.path.splitext(filename)[0] + ".txt"
annotation_path = os.path.join(input_folder, txt_name)
if not os.path.exists(annotation_path):
print(f"[SKIP] 缺少标注文件: {txt_name}")
continue
crop_image_with_annotations(image_path, annotation_path, output_folder)关键改进说明:
- ✅ 多目标支持:使用 for line in f 遍历全部标注行,确保每辆摩托车及其头盔均被独立裁剪;
- ✅ 坐标转换精准:严格按YOLO定义 x1 = (x_c - w/2) * W, y1 = (y_c - h/2) * H 计算左上角,杜绝中心点误用;
- ✅ 边界安全机制:max(0, x1) 和 min(img_width, x2) 防止负坐标或越界索引,避免OpenCV静默失败;
- ✅ 错误防御增强:对空行、格式异常、文件缺失等场景提供明确日志,便于调试;
- ✅ 输出可追溯:生成 xxx_0.jpg, xxx_1.jpg 等命名,清晰对应标注文件中的第N行。
注意事项:
- YOLO标注中 x_c, y_c, w, h 均为 [0,1] 区间归一化值,必须乘以对应图像宽高才能转为像素;
- 若标注工具导出的是Pascal VOC格式(x_min, y_min, x_max, y_max),则无需中心转换,需另行适配;
- 对极小目标(如车牌字符),建议在裁剪后添加 cv2.resize() 放大,避免后续模型识别失真;
- 批量处理前,务必用1–2张图手动验证坐标计算是否与标注可视化工具(如LabelImg)一致。
通过以上修正,您的脚本将稳定输出所有目标的完整、无偏移裁剪图,满足车牌识别、头盔检测等下游任务对数据质量的严苛要求。
立即学习“Python免费学习笔记(深入)”;


















