yolo预标注的txt转换成labelme中segment的json

前言

在yolo预标注的时候,想把保存的txt转换成labelme中segment的json,于是写了下面的脚本。请添加图片描述


1.引入库

完整代码:

import os
import json
from tqdm import tqdm

def get_image_size(image_path):
    from PIL import Image
    with Image.open(image_path) as img:
        width, height = img.size
    return width, height

def txt_to_json(txt_file, image_folder):
    image_file = os.path.join(image_folder, os.path.splitext(os.path.basename(txt_file))[0] + '.png')
    image_width, image_height = get_image_size(image_file)

    shapes = []
    with open(txt_file, 'r') as f:
        for line in f:
            coords = line.strip().split()
            if len(coords) > 1:  # 至少包含 x 和 y 两个坐标
                label = coords[0]
                points = [[float(coords[i]) * image_width, float(coords[i+1]) * image_height] for i in range(1, len(coords), 2)]
                shape = {"label": 'stone',
                         "points": points,
                         "group_id": None,
                         "shape_type": "polygon",
                         "flags": {}}
                shapes.append(shape)

    return {"version": "5.1.1",
            "flags": {},
            "shapes": shapes,
            "imagePath": os.path.basename(image_file),
            "imageData": None,
            "imageHeight": image_height,
            "imageWidth": image_width}

def convert_folder_to_json(folder_path, image_folder, output_folder):
    os.makedirs(output_folder, exist_ok=True)
    for filename in tqdm(os.listdir(folder_path)):
        if filename.endswith('.txt'):
            txt_file = os.path.join(folder_path, filename)
            json_output_file = os.path.join(output_folder, os.path.splitext(filename)[0] + '.json')
            json_data = txt_to_json(txt_file, image_folder)
            with open(json_output_file, 'w') as json_file:
                json.dump(json_data, json_file, indent=4)

if __name__ == '__main__':
    folder_path = r'C:\Users\Lenovo\Downloads\predict3\labels'  # 修改为你的标签文件夹路径
    image_folder = r'C:\Users\Lenovo\Downloads\predict3\images'  # 修改为你的图片文件夹路径
    output_folder = r'C:\Users\Lenovo\Downloads\predict3\labels_json'  # 修改为你的输出文件夹路径
    convert_folder_to_json(folder_path, image_folder, output_folder)

注:这里imageData非常难搞,因为labelme有加密格式,所以设置成null也是可以运行的。

注:这里只写了一个标签,大家可以根据"label": label再修改对应的!

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小张Tt

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值