制作自己的图像分割数据集(VOC格式&CitySpace格式)

本文介绍了如何将已标注的JSON数据转换为VOC格式,包括创建数据集、划分训练集验证集测试集,并以CitySpace数据集为例进行操作。涉及到了图像文件组织、分割标签生成以及数据集划分的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.默认标注好了所有数据,将标注好的json转成VOC分割数据集格式

from __future__ import print_function

import argparse
import glob
import os
import os.path as osp
import sys

import imgviz
import numpy as np

import labelme


def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    parser.add_argument("--input_dir",default="label", help="input annotated directory")
    parser.add_argument("--output_dir",default="data_dataset_voc", help="output dataset directory")
    parser.add_argument("--labels",default="label.txt", help="labels file")
    parser.add_argument(
        "--noviz", help="no visualization", action="store_true"
    )
    args = parser.parse_args()

    if osp.exists(args.output_dir):
        print("Output directory already exists:", args.output_dir)
        sys.exit(1)
    os.makedirs(args.output_dir)
    os.makedirs(osp.join(args.output_dir, "JPEGImages"))
    os.makedirs(osp.join(args.output_dir, "SegmentationClass"))
    os.makedirs(osp.join(args.output_dir, "SegmentationClassPNG"))
    if not args.noviz:
        os.makedirs(
            osp.join(args.output_dir, "SegmentationClassVisualization")
        )
    print("Creating dataset:", args.output_dir)

    class_names = []
    class_name_to_id = {}
    for i, line in enumerate(open(args.labels).readlines()):
        class_id = i - 1  # starts with -1
        class_name = line.strip()
        class_name_to_id[class_name] = class_id
        if class_id == -1:
            assert class_name == "__ignore__"
            continue
        elif class_id == 0:
            assert class_name == "_background_"
        class_names.append(class_name)
    class_names = tuple(class_names)
    print("class_names:", class_names)
    out_class_names_file = osp.join(args.output_dir, "class_names.txt")
    with open(out_class_names_file, "w") as f:
        f.writelines("\n".join(class_names))
    print("Saved class_names:", out_class_names_file)

    for filename in glob.glob(osp.join(args.input_dir, "*.json")):
        print("Generating dataset from:", filename)

        label_file = labelme.LabelFile(filename=filename)

        base = osp.splitext(osp.basename(filename))[0]
        out_img_file = osp.join(args.output_dir, "JPEGImages", base + ".jpg")
        out_lbl_file = osp.join(
            args.output_dir, "SegmentationClass", base + ".npy"
        )
        out_png_file = osp.join(
            args.output_dir, "SegmentationClassPNG", base + ".png"
        )
        if not args.noviz:
            out_viz_file = osp.join(
                args.output_dir,
                "SegmentationClassVisualization",
                base + ".jpg",
            )

        with open(out_img_file, "wb") as f:
            f.write(label_file.imageData)
        img = labelme.utils.img_data_to_arr(label_file.imageData)

        lbl, _ = labelme.utils.shapes_to_label(
            img_shape=img.shape,
            shapes=label_file.shapes,
            label_name_to_value=class_name_to_id,
        )
        labelme.utils.lblsave(out_png_file, lbl)

        np.save(out_lbl_file, lbl)

        if not args.noviz:
            viz = imgviz.label2rgb(
                label=lbl,
                #img改成image,labelme接口的问题不然会报错
                #img=imgviz.rgb2gray(img),
                image=imgviz.rgb2gray(img),
                font_size=15,
                label_names=class_names,
                loc="rb",
            )
            imgviz.io.imsave(out_viz_file, viz)


if __name__ == "__main__":
    main()
label.txt里放
__ignore__
_background_
class1
class2
...

转换成功后有以下几个文件
在这里插入图片描述
JPEGImages里放的是原图,SegmentationClass文件下是npy格的分割数据,SegmentationClassPNG分割需要的mask,SegmentationClassVisualization图像标签叠加的图像,主要看标注有没有出现错误。

2.划分训练验证测试集

from sklearn.model_selection import train_test_split
import os

imagedir = './XXXX/JPEGImages'
outdir = 'voc'
os.makedirs(outdir,exist_ok=True)

images = []
for file in os.listdir(imagedir):
    filename = file.split('.')[0]
    images.append(filename)

# Split the data into training, validation, and test sets (8:1:1 ratio)
train_size = 0.8
val_size = 0.1
test_size = 0.1

train, temp = train_test_split(images, test_size=(val_size + test_size), random_state=0)
val, test = train_test_split(temp, test_size=(test_size / (val_size + test_size)), random_state=0)

# Write the lists to text files
with open(os.path.join(outdir, "train.txt"), 'w') as f:
    f.write('\n'.join(train))

with open(os.path.join(outdir, "val.txt"), 'w') as f:
    f.write('\n'.join(val))

with open(os.path.join(outdir, "test.txt"), 'w') as f:
    f.write('\n'.join(test))

3.cityspace数据集划分脚本

import os
import shutil
import random

def split_data(source_dir, dest_train_dir, dest_val_dir, split_ratio):
    image_dir = os.path.join(source_dir, 'images')
    label_dir = os.path.join(source_dir, 'labels')

    os.makedirs(os.path.join(dest_train_dir, 'images'), exist_ok=True)
    os.makedirs(os.path.join(dest_train_dir, 'labels'), exist_ok=True)
    os.makedirs(os.path.join(dest_val_dir, 'images'), exist_ok=True)
    os.makedirs(os.path.join(dest_val_dir, 'labels'), exist_ok=True)

    image_files = os.listdir(image_dir)
    random.shuffle(image_files)

    num_train = int(len(image_files) * split_ratio)
    train_files = image_files[:num_train]
    val_files = image_files[num_train:]

    for file in train_files:
        image_filename = file
        label_filename = file.replace('.jpg', '.png')

        image_path = os.path.join(image_dir, image_filename)
        label_path = os.path.join(label_dir, label_filename)

        shutil.copy(image_path, os.path.join(dest_train_dir, 'images', image_filename))
        shutil.copy(label_path, os.path.join(dest_train_dir, 'labels', label_filename))

    for file in val_files:
        image_filename = file
        label_filename = file.replace('.jpg', '.png')

        image_path = os.path.join(image_dir, image_filename)
        label_path = os.path.join(label_dir, label_filename)

        shutil.copy(image_path, os.path.join(dest_val_dir, 'images', image_filename))
        shutil.copy(label_path, os.path.join(dest_val_dir, 'labels', label_filename))

# 设置数据集路径和划分比例
source_dir = 'D:/XXXDataSet/dataset'           # 数据集路径
dest_train_dir = 'D:/XXXDataSet/dataset/train'  # 保存训练集的文件夹路径
dest_val_dir = 'D:/XXXDataSet/dataset/test'     # 保存验证集的文件夹路径
split_ratio = 0.8  # 80% 训练集,20% 验证集

split_data(source_dir, dest_train_dir, dest_val_dir, split_ratio)

### 下载 Cityscapes 数据集 为了使用 Cityscapes 数据集进行目标检测,需先从官方网站获取所需的数据文件。官方提供了多个不同用途的压缩包供下载。 #### 官网注册与登录 访问 Cityscapes 的官方网站并完成账号注册和登录过程[^3]。 #### 文件选择与下载 根据需求挑选合适的资源: - **图像数据**:`leftImg8bit_trainvaltest.zip` 包含训练、验证以及测试阶段所需的原始 RGB 图像。 - **精细标注(推荐用于目标检测)**:`gtFine_trainvaltest.zip` 提供了高质量的手动标注结果,适用于精确的目标定位任务;此部分涵盖了实例分割标签等重要信息,对于构建高效能的目标检测模型至关重要[^1]。 - **粗略标注**:虽然 `gtCoarse.zip` 同样包含了大量样本的语义分割标记,但由于其较低的质量标准,在追求高精度的应用场景中通常不被优先考虑。 成功提交请求并通过审核之后即可获得上述资料链接,进而实施批量下载操作。 #### 解压与整理 下载完成后解压缩这些档案到指定的工作目录内。此时会形成如下结构: ``` cityscapes/ ├── leftImg8bit/ │ ├── train/ │ └── val/ └── gtFine/ ├── train/ └── val/ ``` 其中 `leftImg8bit/` 子文件夹保存着未经处理过的街景照片素材,而 `gtFine/` 则对应于细粒度级别的真值描述文档集合[^2]。 #### 转换为适合目标检测框架使用的格式 考虑到大多数流行的目标检测库偏好特定类型的输入形式——比如 Pascal VOC 或 COCO JSON ——因此可能还需要额外步骤来转换现有的 XML 和 PNG 形式的边界框定义至兼容版本。这一步骤具体实现方式取决于所选用的具体工具链和个人喜好[^4]。 ```python import xml.etree.ElementTree as ET from pathlib import Path def convert_xml_to_yolo(xml_file_path, output_dir): tree = ET.parse(xml_file_path) root = tree.getroot() image_width = int(root.find('size').find('width').text) image_height = int(root.find('size').find('height').text) with open(Path(output_dir) / (Path(xml_file_path).stem + '.txt'), 'w') as f: for obj in root.findall('object'): label_name = obj.find('name').text bndbox = obj.find('bndbox') xmin = float(bndbox.find('xmin').text) ymin = float(bndbox.find('ymin').text) xmax = float(bndbox.find('xmax').text) ymax = float(bndbox.find('ymax').text) x_center = ((xmin + xmax) / 2) / image_width y_center = ((ymin + ymax) / 2) / image_height width = abs(xmax - xmin) / image_width height = abs(ymax - ymin) / image_height class_id = get_class_id(label_name) # 需要自定义函数get_class_id()映射类别名称到ID编号 line = f"{class_id} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}\n" f.write(line) for annotation_file in Path('./annotations').glob('*.xml'): convert_xml_to_yolo(annotation_file, './labels') ```
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

VisionX Lab

你的鼓励将是我更新的动力

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

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

打赏作者

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

抵扣说明:

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

余额充值