yolov8训练自己的实例分割数据集

参考:
1、官方教程:https://docs.ultralytics.com/zh/tasks/segment/

2、YOLOv8制作自己的实例分割数据集保姆级教程(包含json转txt)

下载最新yolov8代码

git clone https://github.com/ultralytics/ultralytics.git

一、制作自己的数据集

省略

二、分离img和json 以及json转yolo格式

2.1 分离images和json文件

使用labelme标注完成后的结果是在一个文件夹中。

在这里插入图片描述
分离开来
fenli_image_and_label.py

# 分离jpg txt和json文件import os.path
import xml.etree.ElementTree as ET
from xml.dom.minidom import Document
import os
import os.path
from PIL import Imageimport os
import shutilclass_name = './class.txt'class_new_name = './class_new.txt'
Class_Name = []
Class_new_Name = []
# img_path  = r'/media/huifeimao/2/diyun/11_h264_data/苏州申通5/images/'    #图片文件夹
# xml_path  = r'/media/huifeimao/2/diyun/11_h264_data/苏州申通5/xml/'  #xml文件存放地址
# ann_path  = r'/media/huifeimao/2/diyun/11_h264_data/苏州申通5/0/'# yolov3标注.txt文件夹source_folder="/media/diyun/T9/diyun/10_train_data/9_Chinese_chess/key_point/24_0125_train_183/images_src/"dst_folder="/media/diyun/T9/diyun/10_train_data/9_Chinese_chess/key_point/24_0125_train_183"jpg_destination_folder=dst_folder + "/images"  # 源文件夹路径
txt_destination_folder = dst_folder + "/labels"  # 目标文件夹路径
json_destination_folder= dst_folder + "/json"  # 目标文件夹路径is_delete_src=0def copy_txt_files(source_folder, destination_folder,is_delete_src):# 遍历源文件夹中的所有文件和目录for root, dirs, files in os.walk(source_folder):for file in files:# 检查文件扩展名是否为 .txtif file.endswith(".txt"):# 构建源文件的完整路径source_path = os.path.join(root, file)# 构建目标文件的完整路径destination_path = os.path.join(destination_folder, file)# 复制文件到目标文件夹shutil.copy(source_path, destination_path)if is_delete_src:os.remove(source_path)def copy_json_files(source_folder, destination_folder,is_delete_src):# 遍历源文件夹中的所有文件和目录for root, dirs, files in os.walk(source_folder):for file in files:# 检查文件扩展名是否为 .txtif file.endswith(".json"):# 构建源文件的完整路径source_path = os.path.join(root, file)# 构建目标文件的完整路径destination_path = os.path.join(destination_folder, file)# 复制文件到目标文件夹shutil.copy(source_path, destination_path)if is_delete_src:os.remove(source_path)def copy_jpg_files(source_folder, destination_folder):# 遍历源文件夹中的所有文件和目录for root, dirs, files in os.walk(source_folder):for file in files:# 检查文件扩展名是否为 .txtif file.endswith(".jpg"):# 构建源文件的完整路径source_path = os.path.join(root, file)# 构建目标文件的完整路径destination_path = os.path.join(destination_folder, file)# 复制文件到目标文件夹shutil.copy(source_path, destination_path)if not os.path.exists(txt_destination_folder):os.mkdir(txt_destination_folder)
if not os.path.exists(json_destination_folder):os.mkdir(json_destination_folder)
if not os.path.exists(jpg_destination_folder):os.mkdir(jpg_destination_folder)copy_txt_files(source_folder, txt_destination_folder,is_delete_src)
copy_json_files(source_folder, json_destination_folder,is_delete_src)copy_jpg_files(source_folder, jpg_destination_folder)

2.2、 json转yolo格式

新建segment_json_2_txt.py文件,将代码中的文件路径修改为自己的路径。

❗❗❗代码中第43行的classes中存放的是自己数据集的分类标签,记得修改成自己的。

'''
yolov8训练自己的实例分割数据集json转yolo格式
'''import json
import os
from tqdm import tqdmdef convert_label(json_dir, save_dir, classes):json_paths = os.listdir(json_dir)classes = classes.split(',')for json_path in tqdm(json_paths):path = os.path.join(json_dir, json_path)with open(path, 'r') as load_f:json_dict = json.load(load_f)h, w = json_dict['imageHeight'], json_dict['imageWidth']# save txt pathtxt_path = os.path.join(save_dir, json_path.replace('json', 'txt'))txt_file = open(txt_path, 'w')for shape_dict in json_dict['shapes']:label = shape_dict['label']label_index = classes.index(label)points = shape_dict['points']points_nor_list = []for point in points:points_nor_list.append(point[0] / w)points_nor_list.append(point[1] / h)points_nor_list = list(map(lambda x: str(x), points_nor_list))points_nor_str = ' '.join(points_nor_list)label_str = str(label_index) + ' ' + points_nor_str + '\n'txt_file.writelines(label_str)if __name__ == "__main__":json_dir = '/media/diyun/T9/diyun/10_train_data/9_Chinese_chess/segment/24_0302_train_333/json'save_dir = '/media/diyun/T9/diyun/10_train_data/9_Chinese_chess/segment/24_0302_train_333/labels'classes = 'checkerboard'convert_label(json_dir, save_dir, classes)

在这里插入图片描述

2.3、划分训练和验证集和测试集

将segment_make_train_val_test_txt.py代码中的文件路径修改为自己的路径。

'''
yolov8训练自己的实例分割数据集
yolov8训练,数据集的准备,从yolo的txt 文件,分为预测训练验证
'''import os
import randomtrain_percent = 0.9
trainval_percent = 0.1label_filepath = '/media/diyun/T9/diyun/10_train_data/9_Chinese_chess/segment/24_0302_train_333/labels'  #xml文件存放地址
Imgpath = '/media/diyun/T9/diyun/10_train_data/9_Chinese_chess/segment/24_0302_train_333/images'    #图片文件夹if not os.path.exists('ImageSets/'):os.makedirs('ImageSets/')total_xml = os.listdir(label_filepath)
num = len(total_xml)
list = range(num)
tv = int(num * trainval_percent)
tr = int(tv * train_percent)
print("trainval_percent=",tv)
print("train_percent=",tr)
trainval = random.sample(list, tv)
train = random.sample(trainval, tr)
ftrainval = open('ImageSets/trainval.txt', 'w')
ftest = open('ImageSets/test.txt', 'w')
ftrain = open('ImageSets/train.txt', 'w')
fval = open('ImageSets/val.txt', 'w')for i in list:name = total_xml[i][:-4] + '\n'if i in trainval:ftrainval.write(name)if i in train:ftest.write(name)else:fval.write(name)else:ftrain.write(name)
ftrainval.close()
ftrain.close()
fval.close()
ftest.close()sets = ['train', 'test','val']ImageSets_path='ImageSets/'print(Imgpath)
for image_set in sets:if not os.path.exists('labels/'):os.makedirs('labels/')image_ids = open(ImageSets_path+'%s.txt' % (image_set)).read().strip().split()list_file = open('%s.txt' % (image_set), 'w')for image_id in image_ids:list_file.write(Imgpath+'/%s.jpg\n' % (image_id))list_file.close()

生成如下:
在这里插入图片描述
在这里插入图片描述

2.4、下载预训练模型

https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8s-seg.pt
https://github.com/ultralytics/assets/releases/download/v8.1.0/yolov8l-seg.pt

三、训练

训练配置文件

mytrain_segment_chess_board.yaml

train: /home/diyun/work/python_project/23_0130_xiangqi_yolov5/yolov8/datasets/train.txt  # 生成的train.txt的路径
val: /home/diyun/work/python_project/23_0130_xiangqi_yolov5/yolov8/datasets/val.txt   # 生成的val.txt的路径# Classes
names:0: chess_board

训练代码

yolov8_segment_train.py

from ultralytics import YOLO# 加载模型
#model = YOLO('yolov8s-pose.yaml')  # build a new model from YAML
model = YOLO('./weights/yolov8s-seg.pt')  # load a pretrained model (recommended for training)
#model = YOLO('yolov8s-pose.yaml').load('yolov8s-pose.pt')  # build from YAML and transfer weights# 训练
results = model.train(data='./datasets/mytrain_segment_chess_board.yaml', epochs=100, imgsz=640, workers=0, batch=8, project="Chinese_chess", name="segment")

运行

python yolov8_segment_train.py

或者直接命令行

yolo pose train data=./datasets/mytrain_segment_chess_board.yaml model=yolov8s-seg.pt epochs=100 imgsz=640

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/1487967.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

【日常记录】【JS】对一个数组,按照某个字段的值,进行分组

文章目录 1. 前言2. lodash 的分组3. Object.groupBy()参考链接 1. 前言 在开发中,经常会遇到一组数据,要按照某个字段进行分组,这个时候会有很多种方法,可以使用 forEach、reduce、等其他方法 reduce 方法 function groupBy(arr…

亚马逊云科技 re:Inforce 2024中国站大会

亚马逊云科技 re:Inforce 2024中国站大会 - 生成式AI时代的全面安全,将于7月25日本周四在北京富力万丽酒店揭幕

最新2024海报制作工具免费下载,赶紧体验!

在这个信息爆炸的时代,一张独特而有吸引力的海报如何打动观众的心已经成为每个人都需要关注的问题。如果你感到困惑,那么你就来到了正确的地方。今天我们要讨论的是免费版本的海报制作软件。我们将从软件的选择、操作模式、设计技巧等方面进行详细的解释…

AlibabaCloudAI

快速体验 Spring Cloud Alibaba AI JDK要求最低17 1.SpringAI Spring AI 旨在简化包含人工智能相关功能的应用程序的开发,避免不必要的复杂性。 Spring AI 的核心是提供抽象,作为开发 AI 应用程序的基础。这些抽象有多种实现方式,只需极少…

数据库-小练习

根据题目要求,完成下列任务: 新建表和数据库 //建立数据库 mysql> create database mydb15_indexstu; Query OK, 1 row affected (0.00 sec)//使用数据库 mysql> use mydb15_indexstu; Database changed//创建表student mysql> create table s…

Pytorch深度学习实践(5)逻辑回归

逻辑回归 逻辑回归主要是解决分类问题 回归任务:结果是一个连续的实数分类任务:结果是一个离散的值 分类任务不能直接使用回归去预测,比如在手写识别中(识别手写 0 − − 9 0 -- 9 0−−9),因为各个类别…

【C++初阶】string类

【C初阶】string类 🥕个人主页:开敲🍉 🔥所属专栏:C🥭 🌼文章目录🌼 1. 为什么学习string类? 1.1 C语言中的字符串 1.2 实际中 2. 标准库中的string类 2.1 string类 2.…

栈-链栈的表示和实现

#include<stdio.h> typedef int Status; typedef int sElemType; //链栈 typedef struct StackNode{sElemType data;struct StackNode *next; }StackNode,*LinkStack; StackNode *p; //初始化 Status InitStack(LinkStack &S){SNULL;return 1; } //判空 Status Emp…

[用AI日进斗金系列]用码上飞在企微接单开发一个项目管理系统!

今天是【日进斗金】系列的第二期文章。 先给不了解这个系列的朋友们介绍一下&#xff0c;在这个系列的文章中&#xff0c;我们将会在企微的工作台的“需求发布页面”中寻找有软件开发需求的用户 并通过自研的L4级自动化智能软件开发平台「码上飞CodeFlying」让AI生成应用以解…

一文搞懂深度信念网络!DBN概念介绍与Pytorch实战

前言 本文深入探讨了深度信念网络DBN的核心概念、结构、Pytorch实战&#xff0c;分析其在深度学习网络中的定位、潜力与应用场景。 一、概述 1.1 深度信念网络的概述 深度信念网络&#xff08;Deep Belief Networks, DBNs&#xff09;是一种深度学习模型&#xff0c;代表了一…

Ruoyi-WMS部署

所需软件 1、JDK&#xff1a;8 安装包&#xff1a;https://www.oracle.com/java/technologies/javase/javase8-archive-downloads.htmlopen in new window 安装文档&#xff1a;https://cloud.tencent.com/developer/article/1698454open in new window 2、Redis 3.0 安装包&a…

跨域浏览器解决前端跨域问题

1.问题背景 这是一种属于非主流的解决跨域的方案&#xff0c;但是也是可以正常使用而且比较简单的。如果需要使用主流的解决前端跨域方案&#xff0c;请参考这篇文章。 我这边其实是优先建议大家使用主流的跨域方案&#xff0c;如果主流的实在不行&#xff0c;那么就使用跨域…

redis:清除缓存的最简单命令示例

清除redis缓存命令 1.打开cmd窗口&#xff0c;并cd进入redis所在目录 2.登录redis redis-cli 3.查询指定队列当前的记录数 llen 队列名称 4.清除指定队列所有记录 ltrim 队列名称 1 0 5.再次查询&#xff0c;确认队列的记录数是否已清除

用uniapp 及socket.io做一个简单聊天app 2

在这里只有群聊&#xff0c;二个好友聊天&#xff0c;可以认为是建了一个二人的群聊。 const express require(express); const http require(http); const socketIo require(socket.io); const cors require(cors); // 引入 cors 中间件const app express(); const serv…

探索算法系列 - 双指针

目录 移动零&#xff08;原题链接&#xff09; 复写零&#xff08;原题链接&#xff09; 快乐数&#xff08;原题链接&#xff09; 盛最多水的容器&#xff08;原题链接&#xff09; 有效三角形的个数&#xff08;原题链接&#xff09; 查找总价格为目标值的两个商品&…

科研绘图系列:R语言组合堆积图(stacked barplot with multiple groups)

介绍 通常堆积图的X轴表示样本,样本可能会存在较多的分组信息,通过组合堆积图和样本标签分组信息,我们可以得到一张能展示更多信息的可发表图形。 加载R包 knitr::opts_chunk$set(warning = F, message = F) library(tidyverse) library(cowplot) library(patchwork)导入…

GDAL访问HDFS集群中的数据

1.集群搭建 参考文章&#xff1a;hadoop2.10.0完全分布式集群搭建 HA(QJM)高可用集群搭建_hadoop 2.10 ha-CSDN博客 创建文件夹 hdfs dfs -mkdir -p hdfs://192.168.80.132:9000/test 开放权限 hdfs dfs -chmod -R 777 /test 上传文件 hadoop fs -put /home/wh/data/res…

JavaScript(16)——定时器-间歇函数

开启定时器 setInterval(函数,间隔时间) 作用&#xff1a;每隔一段时间调用这个函数&#xff0c;时间单位是毫秒 例如&#xff1a;每一秒打印一个hello setInterval(function () { document.write(hello ) }, 1000) 注&#xff1a;如果是具名函数的话不能加小括号&#xf…

【论文复现】Vision Transformer(ViT)

1. Transformer结构 1.1 编码器和解码器 翻译这个过程需要中间体。也就是说&#xff0c;编码&#xff0c;解码之间需要一个中介&#xff0c;英文先编码成一个意思&#xff0c;再解码成中文。 那么查字典这个过程就是编码和解码的体现。首先我们的大脑会把它编码&#xff0c;编…

数仓架构解析(第45天)

系列文章目录 经典数仓架构传统离线大数据架构 文章目录 系列文章目录烂橙子-终生成长社群群主&#xff0c;前言1. 经典数仓架构2. 传统离线大数据架构 烂橙子-终生成长社群群主&#xff0c; 采取邀约模式&#xff0c;不支持付费进入。 前言 经典数仓架构 传统离线大数据架…