当前位置: 首页 > news >正文

labelme2yolov8-seg 草稿()

简介:

最近做实例分割分割,使用Labelme生成json格式标签后,需要转换为txt标签,才能供YOLO进行训练。

在参看b站,github后,发现GitHub有相关项目:lableme2yolo

一个是ultralyics官方的JSON2YOLO项目

ultralytics/JSON2YOLO: Convert JSON annotations into YOLO format.

 

参考1:

将labelme数据标注格式转换为YoloV8语义分割数据集,并可自动划分训练集和验证集

import json
import random
import yaml
import argparse
import shutil
from pathlib import Path
from collections import defaultdict
from tqdm import tqdm# 设定随机种子以确保可重复性
random.seed(114514)# yoloV8支持的图像格式
# https://docs.ultralytics.com/modes/predict/?h=format+image#images
image_formats = ["jpg", "jpeg", "png", "bmp", "webp", "tif", ".dng", ".mpo", ".pfm"]def copy_labled_img(json_path: Path, target_folder: Path, task: str):# 遍历支持的图像格式,查找并复制图像文件for format in image_formats:image_path = json_path.with_suffix("." + format)if image_path.exists():# 构建目标文件夹中的目标路径target_path = target_folder / "images" / task / image_path.nameshutil.copy(image_path, target_path)def json_to_yolo(json_path: Path, sorted_keys: list):with open(json_path, "r") as f:labelme_data = json.load(f)width = labelme_data["imageWidth"]height = labelme_data["imageHeight"]yolo_lines = []for shape in labelme_data["shapes"]:label = shape["label"]points = shape["points"]class_idx = sorted_keys.index(label)txt_string = f"{class_idx} "for x, y in points:x /= widthy /= heighttxt_string += f"{x} {y} "yolo_lines.append(txt_string.strip() + "\n")return yolo_linesdef create_directory_if_not_exists(directory_path):# 使用 exist_ok=True 可以避免重复检查目录是否存在directory_path.mkdir(parents=True, exist_ok=True)# 创建训练使用的yaml文件
def create_yaml(output_folder: Path, sorted_keys: list):train_img_path = Path("images") / "train"val_img_path = Path("images") / "val"train_label_path = Path("labels") / "train"val_label_path = Path("labels") / "val"# 创建所需目录for path in [train_img_path, val_img_path, train_label_path, val_label_path]:create_directory_if_not_exists(output_folder / path)names_dict = {idx: name for idx, name in enumerate(sorted_keys)}yaml_dict = {"path": output_folder.as_posix(),"train": train_img_path.as_posix(),"val": val_img_path.as_posix(),"names": names_dict,}yaml_file_path = output_folder / "yolo.yaml"with open(yaml_file_path, "w") as yaml_file:yaml.dump(yaml_dict, yaml_file, default_flow_style=False, sort_keys=False)print(f"yaml created in {yaml_file_path.as_posix()}")# Convert label to idx
def get_labels_and_json_path(input_folder: Path):json_file_paths = list(input_folder.rglob("*.json"))label_counts = defaultdict(int)for json_file_path in json_file_paths:with open(json_file_path, "r") as f:labelme_data = json.load(f)for shape in labelme_data["shapes"]:label = shape["label"]label_counts[label] += 1# 根据标签出现次数排序标签sorted_keys = sorted(label_counts, key=lambda k: label_counts[k], reverse=True)return sorted_keys, json_file_pathsdef labelme_to_yolo(json_file_paths: list, output_folder: Path, sorted_keys: list, split_rate: float
):# 随机打乱 JSON 文件路径列表random.shuffle(json_file_paths)# 计算训练集和验证集的分割点split_point = int(split_rate * len(json_file_paths))train_set = json_file_paths[:split_point]val_set = json_file_paths[split_point:]for json_file_path in tqdm(train_set):txt_name = json_file_path.with_suffix(".txt").nameyolo_lines = json_to_yolo(json_file_path, sorted_keys)output_json_path = Path(output_folder / "labels" / "train" / txt_name)with open(output_json_path, "w") as f:f.writelines(yolo_lines)copy_labled_img(json_file_path, output_folder, task="train")for json_file_path in tqdm(val_set):txt_name = json_file_path.with_suffix(".txt").nameyolo_lines = json_to_yolo(json_file_path, sorted_keys)output_json_path = Path(output_folder / "labels" / "val" / txt_name)with open(output_json_path, "w") as f:f.writelines(yolo_lines)copy_labled_img(json_file_path, output_folder, task="val")if __name__ == "__main__":parser = argparse.ArgumentParser(description="labelme2yolo")parser.add_argument("input_folder", help="输入LabelMe格式文件的文件夹")parser.add_argument("output_folder", help="输出YOLO格式文件的文件夹")parser.add_argument("split_rate", help="调整训练集和测试集的比重")args = parser.parse_args()input_folder = Path(args.input_folder)output_folder = Path(args.output_folder)split_rate = float(args.split_rate)sorted_keys, json_file_paths = get_labels_and_json_path(input_folder)create_yaml(output_folder, sorted_keys)labelme_to_yolo(json_file_paths, output_folder, sorted_keys, split_rate)

参考资料 

1.参考1:KdaiP/labelme2YoloV8-segment: 将labelme数据标注格式转换为YoloV8语义分割数据集,并可自动划分训练集和验证集

2.rooneysh/Labelme2YOLO: 帮助将 LabelMe 注释工具 JSON 格式转换为 YOLO 文本文件格式。如果您已经通过 LabelMe 标记了分割数据集,则可以轻松使用此工具来帮助转换为 YOLO 格式的数据集。 

 

http://www.lryc.cn/news/512910.html

相关文章:

  • 开源简史与概览
  • 充电桩语音提示芯片方案-支持平台自定义语音NV128H让充电更便捷
  • 277-基于八路256Ksps 24bit AD生物电震动检测FMC子卡
  • 【电路理论四】正弦电流电路
  • 【PyCharm】如何把本地整个项目同步到服务器?
  • 露营小程序搭建有哪些步骤?小程序里面可以找个露营搭子
  • SOLID-开闭原则
  • 前端经典面试合集(二)——Vue/React/Node/工程化工具/计算机网络
  • PH47代码框架 24241231 重要更新
  • Qt6之QML——作用域
  • 119.【C语言】数据结构之快速排序(调用库函数)
  • C#封送类
  • 2024年度学习总结
  • 我的博客年度之旅:感恩、成长与展望
  • undefined symbol: __nvJitLinkComplete_12_4, version libnvJitLink.so.12
  • 【OTA】论文笔记--《智能网联汽车整车OTA功能设计研究》智能网联汽车OTA系统设计分析报告
  • c#String和StringBuilder
  • 【Linux】HTTP协议
  • 计算机网络 (14)数字传输系统
  • 《向量数据库指南》——Milvus Cloud 2.5:Sparse-BM25引领全文检索新时代
  • Unity3D 网络框架设计详解
  • 网络渗透测试实验四:CTF实践
  • Wend看源码-Java-Collections 工具集学习
  • [JAVA]MyLogger
  • 玩转OCR | 腾讯云智能结构化OCR初次体验
  • 记一次 dockerfile 的循环依赖错误
  • Trimble天宝X9三维扫描仪为建筑外墙检测提供了全新的解决方案【沪敖3D】
  • 【MySQL】深度学习数据库开发技术:使用CC++语言访问数据库
  • LabVIEW化工实验室设备故障实时监测
  • 单例模式懒汉式、饿汉式(线程安全)