之前跑过一次没有问题,换数据集之后报错了,除此之外还显示ignoring corrupt image/label: could not convert string to float。
查了好久之后发现是标签打错了,json文件转txt的时候没打对,标签名称应该设置成数字才对。忘记从什么地方爬过来的代码重新转txt就没事了。
import json
import os
def convert_labelme_to_yolo(json_file, output_dir, class_mapping):
# 打开并读取 JSON 文件
with open(json_file, 'r', encoding='utf-8') as f:
data = json.load(f)
# 获取图像的宽度和高度
img_width = data['imageWidth']
img_height = data['imageHeight']
# 准备输出文件路径
output_file = os.path.join(output_dir, os.path.splitext(os.path.basename(json_file))[0] + '.txt')
with open(output_file, 'w') as out_f:
for shape in data['shapes']:
label = shape['label']
points = shape['points']
# 计算边界框的 x_min, y_min, x_max, y_max
x_min = min([p[0] for p in points])
y_min = min([p[1] for p in points])
x_max = max([p[0] for p in points])
y_max = max([p[1] for p in points])
# 转换为 YOLO 格式
x_center = (x_min + x_max) / 2.0 / img_width
y_center = (y_min + y_max) / 2.0 / img_height
width = (x_max - x_min) / img_width
height = (y_max - y_min) / img_height
# 获取类别索引
class_id = class_mapping.get(label, -1)
if class_id == -1:
print(f"Warning: label '{label}' not found in class mapping. Skipping.")
continue
# 写入 YOLO 格式
out_f.write(f"{class_id} {x_center} {y_center} {width} {height}\n")
# 定义类别名称到类别索引的映射
class_mapping = {
'stem0': '0',
'stem1': '1',
# 添加其他类别
}
# 使用示例
json_dir = 'E:/code/js9' # 替换为你的 JSON 文件所在的目录
output_dir = 'E:/code/txt9' # 替换为你希望保存 TXT 文件的目录
# 确保输出目录存在
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# 遍历目录中的所有 JSON 文件进行转换
for json_file in os.listdir(json_dir):
if json_file.endswith('.json'):
convert_labelme_to_yolo(os.path.join(json_dir, json_file), output_dir, class_mapping)
stem0和stem1是我用labelme做标注的时候设置的标签,在txt文件里面会把它设置成0和1,这样应该不会报gnoring corrupt image/label: could not convert string to float的错,因为想的是报错因为不能把字符型转成浮点数,所以就设置成数字了。
具体设置的类别可以按照自己的需求修改class_mapping
然后.yaml文件也顺便改了一下
这个相关的其他博客应该有更详细的,我这样就解决了报错问题,仅供参考。