如何计算YOLO v4标注值并解决Custom Vision上传无效区域错误?
解决Custom Vision上传YOLO v4标注数据集时的「Invalid Region」错误
问题核心原因
Custom Vision要求YOLO格式标注必须是基于图像宽高的归一化相对坐标(所有值在0-1之间),而你从Open Images导出的标注大概率是绝对像素坐标,或者数值超出了0-1范围,这就导致了「Invalid Region」错误。对比你成功上传的标注就能发现,成功的标注值都是0-1之间的小数,而失败的标注是大像素值。
标注值计算规则
Custom Vision接受的YOLO v4标注格式为每行对应一个目标,格式如下:
类别ID 归一化中心X 归一化中心Y 归一化宽度 归一化高度
转换步骤(从Open Images的绝对坐标xmin, ymin, xmax, ymax(左上角、右下角像素坐标)转换):
- 获取目标图像的宽度
W、高度H - 计算归一化值:
- 归一化中心X =
(xmin + xmax) / (2 * W) - 归一化中心Y =
(ymin + ymax) / (2 * H) - 归一化宽度 =
(xmax - xmin) / W - 归一化高度 =
(ymax - ymin) / H
- 归一化中心X =
- 强制把所有值限制在0-1之间(避免因标注边界超出图像范围导致的错误)
批量转换代码实现(Python)
以下代码可以批量将Open Images的标注转换为符合Custom Vision要求的格式:
from PIL import Image import os def convert_annotation(image_path, src_label_path, dest_label_path): # 获取图像尺寸 with Image.open(image_path) as img: img_w, img_h = img.size # 读取原标注并转换 with open(src_label_path, 'r') as f: lines = f.read().strip().split('\n') converted = [] for line in lines: if not line: continue # 假设原标注格式:类别ID xmin ymin xmax ymax(绝对像素值) parts = line.split() class_id = parts[0] xmin, ymin, xmax, ymax = map(float, parts[1:5]) # 计算归一化值 cx = (xmin + xmax) / (2 * img_w) cy = (ymin + ymax) / (2 * img_h) w = (xmax - xmin) / img_w h = (ymax - ymin) / img_h # 限制值在0-1区间 cx = max(0.0, min(1.0, cx)) cy = max(0.0, min(1.0, cy)) w = max(0.0, min(1.0, w)) h = max(0.0, min(1.0, h)) converted.append(f"{class_id} {cx:.6f} {cy:.6f} {w:.6f} {h:.6f}") # 保存转换后的标注 with open(dest_label_path, 'w') as f: f.write('\n'.join(converted)) # 批量处理示例 image_folder = "你的图像文件夹路径" src_label_folder = "原Open Images标注文件夹路径" dest_label_folder = "转换后标注保存路径" os.makedirs(dest_label_folder, exist_ok=True) for img_file in os.listdir(image_folder): if img_file.lower().endswith(('.jpg', '.jpeg', '.png')): img_path = os.path.join(image_folder, img_file) label_file = os.path.splitext(img_file)[0] + '.txt' src_label_path = os.path.join(src_label_folder, label_file) dest_label_path = os.path.join(dest_label_folder, label_file) if os.path.exists(src_label_path): convert_annotation(img_path, src_label_path, dest_label_path)
后续验证与上传步骤
- 安装依赖:运行
pip install pillow - 调整代码中的文件夹路径,执行批量转换
- 随机抽取几个转换后的标注文件,对比你之前成功上传的标注格式,确保数值都在0-1之间
- 将转换后的标注文件与对应图像文件名一一对应,按Custom Vision的上传规则(可选择混合格式上传,或按类别分文件夹)上传数据集
内容的提问来源于stack exchange,提问作者ahena
相关产品推荐
相关产品推荐

