上图我的数据格式。

label studio是通过json上传数据个标签,通过下面代码进行转换,其中

import os
import json
import uuid
from PIL import Image
from urllib.request import pathname2url


def convert_yolo_to_ls(images_dir, labels_dir, classes_file, out_file, image_root_url="/data/local-files/?d=train/images",
                       image_ext='.jpg,.jpeg,.png', image_dims=None):
    """Convert YOLO labeling to Label Studio JSON."""

    # Read categories from classes.txt
    with open(classes_file, 'r', encoding='utf-8', errors='ignore') as f:
        lines = [line.strip() for line in f.readlines()]

    categories = {i: line for i, line in enumerate(lines)}
    print(f'Found {len(categories)} categories')

    tasks = []

    # Convert labels for each image
    image_ext = [x.strip() for x in image_ext.split(",")]
    print(f'Looking for images with extensions: {image_ext}')

    for f in os.listdir(images_dir):
        image_file_found_flag = False
        for ext in image_ext:
            if f.endswith(ext):
                image_file = f
                image_file_base = f[0: -len(ext)]
                image_file_found_flag = True
                break
        if not image_file_found_flag:
            continue

        # Build the task for the image
        image_root_url += '' if image_root_url.endswith('/') else '/'
        task = {
            "data": {
                "image": image_root_url + str(pathname2url(image_file))
            }
        }

        # Define corresponding label file and check existence
        label_file = os.path.join(labels_dir, image_file_base + '.txt')

        if os.path.exists(label_file):
            task["annotations"] = [{
                "result": [],
                "ground_truth": False,
            }]

            # Read image size
            if image_dims is None:
                with Image.open(os.path.join(images_dir, image_file)) as im:
                    image_width, image_height = im.size
            else:
                image_width, image_height = image_dims

            # Process the label file
            with open(label_file) as file:
                lines = file.readlines()
                for line in lines:
                    values = line.split()
                    label_id, x, y, width, height = values[0:5]
                    score = float(values[5]) if len(values) >= 6 else None
                    x, y, width, height = (
                        float(x),
                        float(y),
                        float(width),
                        float(height),
                    )
                    item = {
                        "id": uuid.uuid4().hex[0:10],
                        "type": "rectanglelabels",
                        "value": {
                            "x": (x - width / 2) * 100,
                            "y": (y - height / 2) * 100,
                            "width": width * 100,
                            "height": height * 100,
                            "rotation": 0,
                            "rectanglelabels": [categories[int(label_id)]],
                        },
                        "to_name": "image",
                        "from_name": "label",
                        "image_rotation": 0,
                        "original_width": image_width,
                        "original_height": image_height,
                    }
                    if score:
                        item["score"] = score
                    task["annotations"][0]['result'].append(item)

            tasks.append(task)

    if len(tasks) > 0:
        print(f'Saving Label Studio JSON to {out_file}')
        with open(out_file, 'w') as out:
            json.dump(tasks, out)

        print(f'Conversion complete! {len(tasks)} tasks saved to {out_file}')
    else:
        print('No labels converted.')


# Example usage
images_dir = "D:/yolo_xicha/train/images"  # Replace with your image directory
labels_dir = "D:/yolo_xicha/train/labels"  # Replace with your labels directory
classes_file = "D:/yolo_xicha/train/classes.txt"  # Replace with your classes file
out_file = "ls-tasks.json"  # Output file path

convert_yolo_to_ls(images_dir, labels_dir, classes_file, out_file)

其中image_root_url="/data/local-files/?d=train/images",train/images加上启动环境时候的默认路径加起来要是完整的路径。

set LABEL_STUDIO_LOCAL_FILES_SERVING_ENABLED=true

set LABEL_STUDIO_LOCAL_FILES_DOCUMENT_ROOT=D:\\yolo_xicha

随后打开label studio,到设置中,添加源目录。

在导入py生成的json即可完美打开

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐