txt2json

labelme . --labels ./labels.txt  --autosave -o ./annotated --imagelabel ./images --output  ./json

yolo格式的标注文件转成labelme可以查询的json格式
代码如下

import os
import json
from PIL import Image

# 读取图片尺寸
def get_image_size(image_path):
    # 这里可以使用相应的方法获取图片尺寸,例如 PIL 库
    # image_width, image_height = 320, 240  # 假设图片尺寸为 320x240
    # return image_width, image_height
    img = Image.open(image_path)
    # 获取图像尺寸
    image_width, image_height = img.size
    # 返回图像尺寸
    return image_width, image_height


# 转换 YOLO 格式标注为 JSON 格式
def convert_to_json(image_path, annotation_path):
    # 读取图片尺寸
    image_width, image_height = get_image_size(image_path)

    # 读取文本标注文件
    with open(annotation_path, 'r') as f:
        yolo_data = f.readlines()

    # 初始化 JSON 数据结构
    json_data = {
        "version": "5.3.1",
        "flags": {},
        "shapes": [],
        "imagePath": image_path,
        "imageData": None,
        "imageHeight": image_height,
        "imageWidth": image_width
    }

    # 转换为 JSON 格式
    for line in yolo_data:
        data = line.split()
        label = data[0]
        x_center = float(data[1]) * json_data["imageWidth"]
        y_center = float(data[2]) * json_data["imageHeight"]
        width = float(data[3]) * json_data["imageWidth"]
        height = float(data[4]) * json_data["imageHeight"]
        x1 = x_center - width / 2
        y1 = y_center - height / 2
        x2 = x_center + width / 2
        y2 = y_center + height / 2
        shape = {
            "label": label,
            "points": [[x1, y1], [x2, y2]],
            "group_id": None,
            "description": "",
            "shape_type": "rectangle",
            "flags": {}
        }
        json_data["shapes"].append(shape)

    return json_data


# 创建新的文件夹
def create_directory(directory):
    if not os.path.exists(directory):
        os.makedirs(directory)


# 遍历图片文件夹和标注文件夹
image_folder = r"D:\HisCameraImage\datasetv2_240326\downloadIncorrect\images"
annotation_folder = r"D:\HisCameraImage\datasetv2_240326\downloadIncorrect\labels"
output_folder = r"D:\HisCameraImage\datasetv2_240326\downloadIncorrect\json"
create_directory(output_folder)

for root, dirs, files in os.walk(image_folder):
    for file in files:
        if file.endswith(".jpg"):
            image_path = os.path.join(root, file)
            annotation_path = os.path.join(annotation_folder, file[:-4] + ".txt")
            if os.path.exists(annotation_path):
                json_data = convert_to_json(image_path, annotation_path)
                output_path = os.path.join(output_folder, file[:-4] + ".json")
                with open(output_path, 'w') as f:
                    json.dump(json_data, f, indent=4)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值