windows11下将Labelme标注数据转为YOLOV5训练数据集

完整代码:

import shutil
import os
import numpy as np
import json
from glob import glob
import cv2
from sklearn.model_selection import train_test_split
from utils.data_dir import root_dir


def convert(size, box):
    dw = 1. / (size[0])
    dh = 1. / (size[1])
    x = (box[0] + box[1]) / 2.0 - 1
    y = (box[2] + box[3]) / 2.0 - 1
    w = box[1] - box[0]
    h = box[3] - box[2]
    x = x * dw
    w = w * dw
    y = y * dh
    h = h * dh
    return (x, y, w, h)


def generate_mark_data(labelme_path, isUseTest = True):
    """

    Args:
        labelme_path: 标签路径
        isUseTest: 是否创建test集

    Returns:

    """
    # 获取待处理文件
    files = glob(labelme_path + "/*.json")
    files = [i.replace("\\", "/").split("/")[-1].split(".json")[0] for i in files]
    if isUseTest:
        trainval_files, test_files = train_test_split(files, test_size=0.1, random_state=55)
    else:
        trainval_files = files
        test_files = []  # 没有测试集
    train_files, val_files = train_test_split(trainval_files, test_size=0.1, random_state=55)
    return train_files, val_files, test_files


def ChangeToYolo5(yolov5_path, files, classes, txt_Name, img_suffix=".png"):
    tmp_path = f"{labelme_path}/tmp/"
    if not os.path.exists(tmp_path):  # 如果没有tmp文件夹则创建之
        os.makedirs(tmp_path)
    list_file = open(f'{tmp_path}%s.txt' % (txt_Name), 'w')
    for json_file_ in files:
        json_filename = labelme_path + "/" + json_file_ + ".json"
        imagePath = labelme_path + "/" + json_file_ + img_suffix
        list_file.write('%s/%s\n' % (yolov5_path, imagePath))
        out_file = open('%s/%s.txt' % (labelme_path, json_file_), 'w')
        json_file = json.load(open(json_filename, "r", encoding="utf-8"))
        height, width, channels = cv2.imread(labelme_path + "/" + json_file_ + img_suffix).shape
        for multi in json_file["shapes"]:
            points = np.array(multi["points"])
            xmin = min(points[:, 0]) if min(points[:, 0]) > 0 else 0
            xmax = max(points[:, 0]) if max(points[:, 0]) > 0 else 0
            ymin = min(points[:, 1]) if min(points[:, 1]) > 0 else 0
            ymax = max(points[:, 1]) if max(points[:, 1]) > 0 else 0
            label = multi["label"]
            if xmax <= xmin:
                pass
            elif ymax <= ymin:
                pass
            else:
                cls_id = classes.index(label)
                b = (float(xmin), float(xmax), float(ymin), float(ymax))
                bb = convert((width, height), b)
                out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
                print(json_filename, xmin, ymin, xmax, ymax, cls_id)


def make_voc_data(data_path, file_List, pathdepth=9):
    for file in file_List:
        if not os.path.exists(f'{data_path}/VOC/images/%s' % file):
            os.makedirs(f'{data_path}/VOC/images/%s' % file)
        if not os.path.exists(f'{data_path}/VOC/labels/%s' % file):
            os.makedirs(f'{data_path}/VOC/labels/%s' % file)
        f = open(f'{data_path}/LabelmeData/img/8P203/tmp/%s.txt' % file, 'r')
        lines = f.readlines()
        for line in lines:
            line = "/".join(line.split('/')[-pathdepth:]).strip()
            shutil.copy(line, f"{data_path}/VOC/images/%s" % file)
            line = line.replace('jpg', 'txt')
            shutil.copy(line, f"{data_path}/VOC/labels/%s/" % file)


if __name__ == '__main__':
    labelme_path = f"{root_dir}/data/LabelmeData/img/8P203"
    classes = ["1", "2", "3", "4", "5", "6"]
    train_files, val_files, test_files = generate_mark_data(labelme_path)
    yolov5_path = labelme_path
    ChangeToYolo5(yolov5_path, train_files, classes, "train")
    ChangeToYolo5(yolov5_path, val_files, classes, "val")
    ChangeToYolo5(yolov5_path, test_files, classes, "test")
    data_path = f"{root_dir}/data"
    file_List = ["train", "val", "test"]
    make_voc_data(data_path, file_List)
    '''
    file1 = open("tmp/train.txt", "r")
    file2 = open("tmp/val.txt", "r")
    file_list1 = file1.readlines()  # 将所有变量读入列表file_list1
    file_list2 = file2.readlines()  # 将所有变量读入列表file_list2
    file3 = open("tmp/trainval.txt", "w")
    for line in file_list1:
        print(line)
        file3.write(line)
    for line in file_list2:
        print(line)
        file3.write(line)
    '''

其中的路径root_dir来源如下:

要将 labelme 中的多边形标注转为 YOLOv5 的矩形标注,你可以按照以下步骤进行: 1. 首先,使用 labelme 打开需要转换的图片,并使用多边形标注工具对感兴趣的目标进行标注。 2. 然后,将标注好的图片导出为 JSON 文件。 3. 接着,使用 Python 代码读取 JSON 文件,并将多边形标注转换为矩形标注。具体实现可以参考以下代码: ```python import json def polygon_to_yolo(polygon, image_width, image_height): # 将多边形坐标转换为矩形坐标 x_values = [point[0] for point in polygon] y_values = [point[1] for point in polygon] x_min = min(x_values) x_max = max(x_values) y_min = min(y_values) y_max = max(y_values) # 计算矩形中心点坐标和宽高 center_x = (x_min + x_max) / 2 center_y = (y_min + y_max) / 2 width = x_max - x_min height = y_max - y_min # 计算 YOLOv5 格式的坐标和尺寸 x_center = center_x / image_width y_center = center_y / image_height box_width = width / image_width box_height = height / image_height return x_center, y_center, box_width, box_height with open('labelme_annotation.json', 'r') as f: data = json.load(f) image_width = data['imageWidth'] image_height = data['imageHeight'] shapes = data['shapes'] for shape in shapes: polygon = shape['points'] label = shape['label'] x_center, y_center, box_width, box_height = polygon_to_yolo(polygon, image_width, image_height) print(f"{label} {x_center} {y_center} {box_width} {box_height}") ``` 这段代码将读取名为 `labelme_annotation.json` 的 JSON 文件,并将其中的多边形标注转换为 YOLOv5 的矩形标注。最终输出的格式为:`label x_center y_center box_width box_height`。 4. 最后,将输出的矩形标注写入到 YOLOv5 格式的标注文件中即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Trisyp

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

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

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

打赏作者

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

抵扣说明:

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

余额充值