文章目录
- 前言
- 一、数据集制作
- 二、模型训练推理:
前言
随着深度学习技术的不断发展,目标检测与分割技术在计算机视觉领域扮演着越来越重要的角色。YOLO(You Only Look Once)作为一种高效、实时的目标检测算法,自提出以来就受到了广泛关注。YOLOv11-seg作为YOLO系列算法的最新成员,不仅继承了YOLO系列的高效性,还引入了分割功能,使得该算法在目标检测与分割任务中具有更广泛的应用前景。
本文将详细介绍YOLOv11-seg数据集的制作、训练和推理流程,旨在为相关领域的科研人员、工程师和爱好者提供一个完整的实践指南。通过本文的介绍,读者可以了解如何从原始数据出发,经过数据预处理、标注、模型训练和推理等步骤,最终得到一个高效的目标检测与分割模型。
一、数据集制作
首先下载labelme:
下载方式:
#创建虚拟环境:
conda create -n labelme python=3.8
conda activate labelme
#安装labelme
pip install labelme
#打开
labelme
打开目录选择自己的图片
点击编辑-创建多边形-进行标注
标注好之后会生成json标签
使用下面代码将json转化为txt:
# -*- coding: utf-8 -*-
import json
import os
import argparse
from tqdm import tqdmdef 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 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__":"""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=r'F:\1109\json',help='json path dir')parser.add_argument('--save-dir', type=str, default=r'F:\1109/txt',help='txt save dir')parser.add_argument('--classes', type=str, default='box', help='classes')args = parser.parse_args()json_dir = args.json_dirsave_dir = args.save_dirclasses = args.classesconvert_label_json(json_dir, save_dir, classes)
使用如下代码划分数据集:
# 将图片和标注数据按比例切分为 训练集和测试集
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.85val_percent = 0.15test_percent = 0total_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_valtrain = random.sample(list_all_txt, num_train)# 在全部数据集中取出trainval_test = [i for i in list_all_txt if not i in train]# 再从val_test取出num_val个元素,val_test剩下的元素就是testval = 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=r'F:\1109',help='image path dir')parser.add_argument('--txt-dir', type=str, default=r'F:\1109\txt',help='txt path dir')parser.add_argument('--save-dir', default=r'F:\1109\ccc', type=str,help='save dir')args = parser.parse_args()image_dir = args.image_dirtxt_dir = args.txt_dirsave_dir = args.save_dirmain(image_dir, txt_dir, save_dir)
效果:
至此数据集的制作已经完成,接下来开始模型训练。
二、模型训练推理:
制作yaml文件,将训练路径写入文件中:
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
#path: ../VOCdevkit_wpeson_Tanker_01-20/VOC2007/ImageSets/Main
train: /home/build/ccc/images/train/ # train images (relative to 'path') 16551 imagesval: /home/build/ccc/images/val/# train images (relative to 'path') 16551 images
#val: # val images (relative to 'path') 4952 images
# - val.txt
#test: # test images (optional)
# - test.txt# Classes
nc: 1 # number of classes
names: ['box'] # class names
运行下面代码进行模型训练:
from ultralytics import YOLO# Load a model
model = YOLO("/home/build/下载/ultralytics-main (1)/yolo11n-seg.pt") # load a pretrained model (recommended for training)# Train the model with 2 GPUs
results = model.train(data="/home/build/ccc/ccc.yaml", epochs=100, imgsz=640, device="cpu")
模型训练好之后运行下面代码进行推理测试:
from ultralytics import YOLO# Load a model
model = YOLO("yolo11n.pt") # pretrained YOLO11n model# Run batched inference on a list of images
results = model(["image1.jpg", "image2.jpg"]) # return a list of Results objects# Process results list
for result in results:boxes = result.boxes # Boxes object for bounding box outputsmasks = result.masks # Masks object for segmentation masks outputskeypoints = result.keypoints # Keypoints object for pose outputsprobs = result.probs # Probs object for classification outputsobb = result.obb # Oriented boxes object for OBB outputsresult.show() # display to screenresult.save(filename="result.jpg") # save to disk