参考文献
https://blog.csdn.net/qq_51539952/article/details/136361107
https://blog.csdn.net/m0_51530640/article/details/129975257
感谢两位的描述
当然。上述已经很精细了
我这里是我自己做一个总结与备份
(1)制作数据集
安装:pip install labelme
任意文件下下面新建txt、images、json、split四个文件夹
然后记得点一下“文件-自动保存”
然后把json、图的数据放到对应的文件夹内
这里由于保存的是json所以要更新为txt格式,记得修改路径
# -*- coding: utf-8 -*-
import json
import os
import argparse
from tqdm import tqdm
def convert_label_json(json_dir, save_dir, classes):
json_paths = os.listdir(json_dir)
classes = classes.split(',')
for json_path in tqdm(json_paths):
# for json_path in 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 path
txt_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__":
"""
python json2txt_nomalize.py --json-dir my_datasets/color_rings/jsons --save-dir my_datasets/color_rings/txts --classes "cat,dogs"
"""
parser = argparse.ArgumentParser(description='json convert to txt params')
parser.add_argument('--json-dir', type=str,default='D:/ultralytics-main/data/json', help='json path dir')#这个地方换成自己的json的文件夹
parser.add_argument('--save-dir', type=str,default='D:/ultralytics-main/data/txt' ,help='txt save dir')#这个地方换成自己的txt的文件夹
parser.add_argument('--classes', type=str, default='ccc,ccc1',help='classes')#这个地方换成自己的类别,“类别1,类别2”
args = parser.parse_args()
json_dir = args.json_dir
save_dir = args.save_dir
classes = args.classes
convert_label_json(json_dir, save_dir, classes)
(2)划分数据集
在当前文件夹下运行,记得更换一下下面的路径
# 将图片和标注数据按比例切分为 训练集和测试集
import shutil
import random
import os
import argparse
# 检查文件夹是否存在
def mkdir(path):
if not os.path.exists(path):
os.makedirs(path)
def main(image_dir, txt_dir, save_dir):
# 创建文件夹
mkdir(save_dir)
images_dir = os.path.join(save_dir, 'images')
labels_dir = os.path.join(save_dir, 'labels')
img_train_path = os.path.join(images_dir, 'train')
img_test_path = os.path.join(images_dir, 'test')
img_val_path = os.path.join(images_dir, 'val')
label_train_path = os.path.join(labels_dir, 'train')
label_test_path = os.path.join(labels_dir, 'test')
label_val_path = os.path.join(labels_dir, 'val')
mkdir(images_dir);
mkdir(labels_dir);
mkdir(img_train_path);
mkdir(img_test_path);
mkdir(img_val_path);
mkdir(label_train_path);
mkdir(label_test_path);
mkdir(label_val_path);
# 数据集划分比例,训练集75%,验证集15%,测试集15%,按需修改
train_percent = 0.8
val_percent = 0.1
test_percent = 0.1
total_txt = os.listdir(txt_dir)
num_txt = len(total_txt)
list_all_txt = range(num_txt) # 范围 range(0, num)
num_train = int(num_txt * train_percent)
num_val = int(num_txt * val_percent)
num_test = num_txt - num_train - num_val
train = random.sample(list_all_txt, num_train)
# 在全部数据集中取出train
val_test = [i for i in list_all_txt if not i in train]
# 再从val_test取出num_val个元素,val_test剩下的元素就是test
val = random.sample(val_test, num_val)
print("训练集数目:{}, 验证集数目:{},测试集数目:{}".format(len(train), len(val), len(val_test) - len(val)))
for i in list_all_txt:
name = total_txt[i][:-4]
srcImage = os.path.join(image_dir, name + '.jpg')
srcLabel = os.path.join(txt_dir, name + '.txt')
if i in train:
dst_train_Image = os.path.join(img_train_path, name + '.jpg')
dst_train_Label = os.path.join(label_train_path, name + '.txt')
shutil.copyfile(srcImage, dst_train_Image)
shutil.copyfile(srcLabel, dst_train_Label)
elif i in val:
dst_val_Image = os.path.join(img_val_path, name + '.jpg')
dst_val_Label = os.path.join(label_val_path, name + '.txt')
shutil.copyfile(srcImage, dst_val_Image)
shutil.copyfile(srcLabel, dst_val_Label)
else:
dst_test_Image = os.path.join(img_test_path, name + '.jpg')
dst_test_Label = os.path.join(label_test_path, name + '.txt')
shutil.copyfile(srcImage, dst_test_Image)
shutil.copyfile(srcLabel, dst_test_Label)
if __name__ == '__main__':
"""
python split_datasets.py --image-dir my_datasets/color_rings/imgs --txt-dir my_datasets/color_rings/txts --save-dir my_datasets/color_rings/train_data
"""
parser = argparse.ArgumentParser(description='split datasets to train,val,test params')
parser.add_argument('--image-dir', type=str,default='D:/ultralytics-main/data', help='image path dir')#换成自己的images文件夹
parser.add_argument('--txt-dir', type=str,default='D:/ultralytics-main/data/txt' , help='txt path dir')#换成自己的txt文件夹
parser.add_argument('--save-dir', default='D:/ultralytics-main/data/split',type=str, help='save dir')#换成自己的split文件夹
args = parser.parse_args()
image_dir = args.image_dir
txt_dir = args.txt_dir
save_dir = args.save_dir
main(image_dir, txt_dir, save_dir)
(3)修改数据集的配置文件ultralytics-main\ultralytics\cfg\datasets\coco128-seg.yaml ,换上自己数据集的路径以及标签名称,和目标检测一样;
修改model的配置文件ultralytics-main\ultralytics\cfg\models\v8\yolov8-seg.yaml 下的类别,将80类换成自己的类别个数。
这里可以看一下
https://blog.csdn.net/qq_51539952/article/details/136361107
(4)训练
记得更新路径
from ultralytics import YOLO
# load a model
model = YOLO(r"F:\detection\fenge\ultralytics-main\ultralytics\cfg\models\v8/yolov8-seg.yaml")#换成自己的配置
model = YOLO(r"F:\detection\ultralytics-main/yolov8n.pt")
# Train the model#语义分割换成yolov8n-seg.pt
model.train(data=r'F:\detection\fenge\ultralytics-main\ultralytics\cfg\datasets/coco128-seg.yaml', epochs=500,
imgsz=640)#换成自己的配置
(5)预测
记得更新路径
from ultralytics import YOLO
from PIL import Image
from ultralytics import YOLO
# Load a model
model = YOLO(r"F:\detection\fenge\ultralytics-main/runs\detect\train7/weights/best.pt") # load an official model
# model = YOLO('path/to/best.pt') # load a custom model#自己训练的最优的模型参数
# Predict with the model
results = model(
r"F:\detection\fenge\ultralytics-main/25.jpg") # predict on an image#测试图
# Show the results
for r in results:
im_array = r.plot() # plot a BGR numpy array of predictions
im = Image.fromarray(im_array[..., ::-1]) # RGB PIL image
im.show() # show image