yolov8自定义实例分割

1.yolo实例分割数据集格式与标注 标注工具labelImg使用方法-CSDN博客(没有多边形的绘制方式)下载: github.com windows直接下载exe.

下载好后与之前的操作都一样,由于labelmg生成的是json文件需要重新写一个脚本生成txt文件,之后和之前一样

之前文章

数据集构建与训练前准备-CSDN博客

模型推理测试与导出-CSDN博客

注意的是实例分割模型训练要用

yolo task=segment mode=train model=yolov8s-seg.pt epochs=5 batch=1
data=co2_dataset.yaml


转化脚本

import json

import os

def json2txt():

json_dir = "C:/yolov8study/cs"

train_label_dir = "C:/yolov8study/cs/1"

valid_label_dir = "C:/yolov8study/cs/2"

确保标签目录存在

if not os.path.exists(train_label_dir):

os.makedirs(train_label_dir)

if not os.path.exists(valid_label_dir):

os.makedirs(valid_label_dir)

files = os.listdir(json_dir)

for json_file in files:

if not json_file.endswith(".json"):

print(f"跳过非 JSON 文件: {json_file}")

continue

json_path = os.path.join(json_dir, json_file)

print(f"正在处理 JSON 文件: {json_file}")

with open(json_path, 'r') as f:

data = json.load(f)

直接从 JSON 数据中获取图像宽高信息

img_width = data.get("imageWidth")

img_height = data.get("imageHeight")

img_name = data.get("imagePath")

if img_name and img_width and img_height:

生成对应的 TXT 文件路径

if img_name.endswith("bmp"):

img_name = img_name.replace("bmp", "jpg")

if img_name.endswith("png"):

img_name = img_name.replace("png", "jpg")

判断 json_dir 路径中是否包含 "valid" 或 "train"

if "valid" in json_dir.lower():

current_label_dir = valid_label_dir

elif "train" in json_dir.lower():

current_label_dir = train_label_dir

else:

print(f"无法确定标签目录,默认使用训练集目录。JSON 文件: {json_file}")

current_label_dir = train_label_dir

data_label_text_f = os.path.join(current_label_dir, img_name.replace(".jpg", ".txt"))

shapes = data.get("shapes", [])

if not shapes:

print(f"JSON 文件 {json_file} 中的 shapes 列表为空,生成的 TXT 文件将为空。")

with open(data_label_text_f, 'w') as file_write_obj:

类别索引固定为 0(只有 cs 标签),仅输出一次

clazz_index = 0

file_write_obj.write(f"{clazz_index}")

遍历所有目标对象

for shape in shapes:

points = shape.get("points", [])

遍历 points 数组中的每个点

for point in points:

x = float(point[0])

y = float(point[1])

转换为 YOLO 格式(仅保留中心点坐标)

cx = x / img_width

cy = y / img_height

写入 TXT 文件,不换行

file_write_obj.write(f" {cx:.6f} {cy:.6f}")

最后添加换行符

file_write_obj.write("\n")

print(f"已处理图像: {img_name},生成标签文件: {data_label_text_f}")

else:

print(f"JSON 文件 {json_file} 缺少必要的图像信息,跳过处理。")

if name == "main":

json2txt()

相关推荐
lucky_lyovo4 分钟前
卷积神经网络--网络性能提升
人工智能·神经网络·cnn
liliangcsdn8 分钟前
smolagents - 如何在mac用agents做简单算术题
人工智能·macos·prompt
nju_spy12 分钟前
周志华《机器学习导论》第8章 集成学习 Ensemble Learning
人工智能·随机森林·机器学习·集成学习·boosting·bagging·南京大学
静心问道36 分钟前
TrOCR: 基于Transformer的光学字符识别方法,使用预训练模型
人工智能·深度学习·transformer·多模态
说私域38 分钟前
基于开源AI大模型、AI智能名片与S2B2C商城小程序源码的用户价值引导与核心用户沉淀策略研究
人工智能·开源
亲持红叶39 分钟前
GLU 变种:ReGLU 、 GEGLU 、 SwiGLU
人工智能·深度学习·神经网络·激活函数
说私域39 分钟前
线上协同办公时代:以开源AI大模型等工具培养网感,拥抱职业变革
人工智能·开源
群联云防护小杜41 分钟前
深度隐匿源IP:高防+群联AI云防护防绕过实战
运维·服务器·前端·网络·人工智能·网络协议·tcp/ip
摘星编程1 小时前
构建智能客服Agent:从需求分析到生产部署
人工智能·需求分析·智能客服·agent开发·生产部署
不爱学习的YY酱1 小时前
信息检索革命:Perplexica+cpolar打造你的专属智能搜索中枢
人工智能