一、coco数据集下载

1、官网下载

首先,我们要下载COCO数据集,本文主要使用的是COCO2014和COCO2017,因为是国外数据集,因此下载需要翻墙下载。参考博文原文链接:https://blog.csdn.net/qq_41847324/article/details/86224628

COCO数据集有91类,虽然比ImageNet和SUN类别少,但是每一类的图像多,这有利于获得更多的每类中位于某种特定场景的能力,对比PASCAL VOC,其有更多类和图像。


MSCOCO数据集的官网为:http://mscoco.org/
具体来说,如果想只下载COCO2017/COCO2014的话,可以不需要翻墙下载,复制以下链接打开迅雷等下载软件下载即可,网速还可以。
COCO2017 训练数据:http://images.cocodataset.org/zips/train2017.zip
http://images.cocodataset.org/annotations/annotations_trainval2017.zip
COCO2017验证数据:http://images.cocodataset.org/zips/val2017.zip
http://images.cocodataset.org/annotations/stuff_annotations_trainval2017.zip
COCO2017测试数据集:http://images.cocodataset.org/zips/test2017.zip
http://images.cocodataset.org/annotations/image_info_test2017.zip

COCO2014的相关数据只需要将以上链接中的7改成4即可。

2、下载目录所示

3、转换好的txt标签


原文链接:https://blog.csdn.net/m0_60139002/article/details/153561768

下载COCO数据集

✅ 图像数据
http://images.cocodataset.org/zips/train2017.zip

http://images.cocodataset.org/zips/val2017.zip

http://images.cocodataset.org/zips/test2017.zip

✅ 标签文件

https://github.com/ultralytics/assets/releases/download/v0.0.0/coco2017labels-segments.zip

4、json准换为txt标签代码

coco_make_seg_labels.py

训练集和验证集

import os
import json
from tqdm import tqdm
import argparse
import numpy as np

# 生成训练集标签(替换为自己的路径)
# json_path = r'E:\COCO dataset\annotations_trainval2017\instances_train2017.json'
# label_path = r'D:\your\ultralytics-main\datasets\labels\train2017'

# 生成验证集标签(替换为自己的路径)
json_path = r'E:\COCO dataset\annotations_trainval2017\instances_val2017.json'
label_path = r'D:\your\datasets/labels/val2017'  # 修正路径分隔符(统一用/)

parser = argparse.ArgumentParser()
parser.add_argument('--json_path', default=json_path, type=str,
                    help="input: coco format(json)")
parser.add_argument('--save_path', default=label_path, type=str,
                    help="specify where to save the output dir of labels")
arg = parser.parse_args()


def convert_bbox(size, box):
    """转换边界框为YOLO格式(归一化xywh)"""
    dw = 1. / (size[0])
    dh = 1. / (size[1])
    x = box[0] + box[2] / 2.0  # 中心x
    y = box[1] + box[3] / 2.0  # 中心y
    w = box[2]  # 宽度
    h = box[3]  # 高度
    x = x * dw
    w = w * dw
    y = y * dh
    h = h * dh
    return (x, y, w, h)


def convert_seg(size, seg_xy):
    """转换分割掩码多边形坐标为YOLO格式(归一化)"""
    dw = 1. / (size[0])
    dh = 1. / (size[1])
    seg_xy = np.array(seg_xy).reshape(-1, 2)  # 重塑为[N,2]的坐标矩阵
    seg_xy[:, 0] = seg_xy[:, 0] * dw  # x坐标归一化
    seg_xy[:, 1] = seg_xy[:, 1] * dh  # y坐标归一化
    return seg_xy.flatten().tolist()  # 展平为一维列表


if __name__ == '__main__':
    json_file = arg.json_path  # COCO Instance分割标注文件
    ana_txt_save_path = arg.save_path  # 标签保存路径

    # 创建保存目录
    if not os.path.exists(ana_txt_save_path):
        os.makedirs(ana_txt_save_path)

    # 加载COCO标注数据
    with open(json_file, 'r', encoding='utf-8') as f:
        data = json.load(f)

    # 建立COCO类别ID到YOLO类别ID的映射(从0开始)
    id_map = {}
    for i, category in enumerate(data['categories']):
        id_map[category['id']] = i
    print(f"类别映射表:{id_map}")

    # 构建图像ID到标注ID的映射(降低时间复杂度)
    img_ann_dict = {}
    for ann in data['annotations']:
        img_id = ann['image_id']
        if img_id not in img_ann_dict:
            img_ann_dict[img_id] = []
        img_ann_dict[img_id].append(ann)

    # 逐图像生成标签文件
    for img in tqdm(data['images'], desc="转换标签"):
        img_id = img['id']
        img_width = img['width']
        img_height = img['height']
        filename = img['file_name']
        # 生成txt文件名(与图像名一致)
        txt_name = os.path.splitext(filename)[0] + '.txt'
        txt_path = os.path.join(ana_txt_save_path, txt_name)

        with open(txt_path, 'w', encoding='utf-8') as f_txt:
            # 跳过无标注的图像
            if img_id not in img_ann_dict:
                continue
            # 处理该图像的所有标注
            for ann in img_ann_dict[img_id]:
                # 跳过无分割掩码的标注(如仅检测标注)
                if 'segmentation' not in ann or len(ann['segmentation']) == 0:
                    continue
                # 1. 转换边界框(检测标签)
                bbox = convert_bbox((img_width, img_height), ann['bbox'])
                # 2. 转换分割掩码(取第一个多边形,COCO可能有多个)
                seg_xy = ann['segmentation'][0]  # 取第一个分割多边形
                seg_xy_norm = convert_seg((img_width, img_height), seg_xy)
                # 跳过无效的分割坐标(点数<3无法构成多边形)
                if len(seg_xy_norm) < 6:
                    continue
                # 3. 写入标签:类别ID + 边界框 + 分割坐标
                line = [str(id_map[ann['category_id']])]  # 类别ID
                line += [f"{x:.6f}" for x in bbox]  # 边界框(xywh)
                line += [f"{x:.6f}" for x in seg_xy_norm]  # 分割坐标
                f_txt.write(' '.join(line) + '\n')

    print(f"标签转换完成!保存路径:{ana_txt_save_path}")

5、转换完后对应数据集结构

6、生成txt目录 make_txt.py

需要保存在images与labels同级目录下

import os


# folder_path = r"D:\images\train"  # 替换为你的文件夹路径
# output_file = r"D:\train.txt"  # 存储结果的txt文件


# folder_path = r"D:\images\val"  # 替换为你的文件夹路径
# output_file = r"D:\val.txt"  # 存储结果的txt文件

folder_path = r"D:\images\test"  # 替换为你的文件夹路径
output_file = r"D:\test.txt"  # 存储结果的txt文件

# 创建输出文件的目录(不是创建文件本身)
output_dir = os.path.dirname(output_file)

os.makedirs(output_dir, exist_ok=True)  # 这里创建的是目录,不是文件
# 获取文件夹中所有文件的绝对路径
file_paths = [os.path.join(folder_path, f) for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]

# 将文件路径按行写入txt文件
with open(output_file, "w") as f:
    for file_path in file_paths:
        f.write(file_path + "\n")

print(f"文件路径已存储在 {output_file} 中。")

结构如下图

二、训练

1、yolo11环境配置

参照:ultralytics/ultralytics: Ultralytics YOLO 🚀

2、修改coco.yaml文件

# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license

# COCO 2017 dataset https://cocodataset.org by Microsoft
# Documentation: https://docs.ultralytics.com/datasets/detect/coco/
# Example usage: yolo train data=coco.yaml
# parent
# ├── ultralytics
# └── datasets
#     └── coco  ← downloads here (20.1 GB)

# 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: ../datasets/coco # dataset root dir
#train: train2017.txt # train images (relative to 'path') 118287 images
#val: val2017.txt # val images (relative to 'path') 5000 images
#test: test-dev2017.txt # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794

path: D:\ultralytics-main\datasets\ # dataset root dir
train: train.txt # train images (relative to 'path') 118287 images
val: val.txt # val images (relative to 'path') 5000 images
#test: test-dev2017.txt # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794
# Classes
names:
  0: person
  1: bicycle
  2: car
  3: motorcycle
  4: airplane
  5: bus
  6: train
  7: truck
  8: boat
  9: traffic light
  10: fire hydrant
  11: stop sign
  12: parking meter
  13: bench
  14: bird
  15: cat
  16: dog
  17: horse
  18: sheep
  19: cow
  20: elephant
  21: bear
  22: zebra
  23: giraffe
  24: backpack
  25: umbrella
  26: handbag
  27: tie
  28: suitcase
  29: frisbee
  30: skis
  31: snowboard
  32: sports ball
  33: kite
  34: baseball bat
  35: baseball glove
  36: skateboard
  37: surfboard
  38: tennis racket
  39: bottle
  40: wine glass
  41: cup
  42: fork
  43: knife
  44: spoon
  45: bowl
  46: banana
  47: apple
  48: sandwich
  49: orange
  50: broccoli
  51: carrot
  52: hot dog
  53: pizza
  54: donut
  55: cake
  56: chair
  57: couch
  58: potted plant
  59: bed
  60: dining table
  61: toilet
  62: tv
  63: laptop
  64: mouse
  65: remote
  66: keyboard
  67: cell phone
  68: microwave
  69: oven
  70: toaster
  71: sink
  72: refrigerator
  73: book
  74: clock
  75: vase
  76: scissors
  77: teddy bear
  78: hair drier
  79: toothbrush

# Download script/URL (optional)
download: |
  from ultralytics.utils.downloads import download
  from pathlib import Path

  # Download labels
  segments = True  # segment or box labels
  dir = Path(yaml['path'])  # dataset root dir
  url = 'https://github.com/ultralytics/assets/releases/download/v0.0.0/'
  urls = [url + ('coco2017labels-segments.zip' if segments else 'coco2017labels.zip')]  # labels
  download(urls, dir=dir.parent)
  # Download data
  urls = ['http://images.cocodataset.org/zips/train2017.zip',  # 19G, 118k images
          'http://images.cocodataset.org/zips/val2017.zip',  # 1G, 5k images
          'http://images.cocodataset.org/zips/test2017.zip']  # 7G, 41k images (optional)
  download(urls, dir=dir / 'images', threads=3)

3、训练代码

from ultralytics import YOLO

if __name__ == '__main__':
    model = YOLO(r'ultralytics/cfg/models/11/yolo11m-seg.yaml')
    model.train(data=r'coco.yaml',
                imgsz=640,
                epochs=100,
                single_cls=True,
                batch=2,
                workers=1,
                device='0',
                )

在ultralytics-main\runs\segment\train下会生成训练结果

4、预测代码

from ultralytics import YOLO

# 加载预训练的YOLOv11n模型
model = YOLO(r"runs/segment/train9/weights/best.pt")

# 对指定的图像文件夹进行推理,并设置各种参数
results = model.predict(
    source=r"D:\images\val",  # 数据来源,可以是文件夹、图片路径、视频、URL,或设备ID(如摄像头)
    conf=0.45,  # 置信度阈值  0.45
    iou=0.6,  # IoU 阈值
    imgsz=640,  # 图像大小
    half=False,  # 使用半精度推理
    device=None,  # 使用设备,None 表示自动选择,比如'cpu','0'
    max_det=300,  # 最大检测数量
    vid_stride=1,  # 视频帧跳跃设置
    stream_buffer=False,  # 视频流缓冲
    visualize=False,  # 可视化模型特征
    augment=False,  # 启用推理时增强
    agnostic_nms=False,  # 启用类无关的NMS
    classes=None,  # 指定要检测的类别
    retina_masks=False,  # 使用高分辨率分割掩码
    embed=None,  # 提取特征向量层
    show=False,  # 是否显示推理图像
    save=True,  # 保存推理结果
    save_frames=False,  # 保存视频的帧作为图像
    save_txt=True,  # 保存检测结果到文本文件
    save_conf=False,  # 保存置信度到文本文件
    save_crop=False,  # 保存裁剪的检测对象图像
    show_labels=True,  # 显示检测的标签
    show_conf=True,  # 显示检测置信度
    show_boxes=True,  # 显示检测框
    line_width=None  # 设置边界框的线条宽度,比如2,4
)

5、其他

学习中 也可参考

(99+ 封私信 / 81 条消息) 【ultralytics-PART: 02】实例分割数据格式转换coco2yolo - 知乎https://zhuanlan.zhihu.com/p/717995473Python将COCO格式实例分割数据集转换为YOLO格式实例分割数据集_coco转yolo-CSDN博客https://blog.csdn.net/FriendshipTang/article/details/131979248语义分割:YOLOv11的分割模型训练自己的数据集(从代码下载到实例测试)_yolov11语义分割-CSDN博客https://blog.csdn.net/qq_42591591/article/details/142656497?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7EPaidSort-1-142656497-blog-145900119.235%5Ev43%5Epc_blog_bottom_relevance_base2&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7EPaidSort-1-142656497-blog-145900119.235%5Ev43%5Epc_blog_bottom_relevance_base2&utm_relevant_index=1

Instance Segmentation - Ultralytics YOLO Docshttps://docs.ultralytics.com/tasks/segment/(99+ 封私信 / 81 条消息) 芒果Ultralytics最新YOLO11算法原理解析-包含最新结构图以及内附YOLO11各部分细致结构图 - 知乎https://zhuanlan.zhihu.com/p/7247937963全新YOLOv11一文弄懂 | YOLOv11网络结构解读 、yolov11.yaml配置文件详细解读与说明、模型训练参数详细解析 | 通俗易懂!入门必看系列!_yolov11网络结构图详解-CSDN博客https://blog.csdn.net/qq_45972324/article/details/150154900YOLOv8-seg训练与推理 - wancy - 博客园https://www.cnblogs.com/wancy/p/18442457

YOLO11 实例分割 | 自动标注 | 预标注 | 标签格式转换 | 手动校正标签_yolov11实例分割-CSDN博客https://blog.csdn.net/qq_41204464/article/details/142895716?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_utm_term~default-4-142895716-blog-126816004.235^v43^pc_blog_bottom_relevance_base2&spm=1001.2101.3001.4242.3&utm_relevant_index=7ultralytics:ultralytics - 提供 YOLOv8 模型,用于目标检测、图像分割、姿态估计和图像分类,适合机器学习和计算机视觉领域的开发者。 - AtomGit | GitCodehttps://gitcode.com/GitHub_Trending/ul/ultralytics

在计算机视觉领域,图像分割是一个重要的研究方向,而高质量的数据集则是推动该领域发展的关键。Coco128-Seg数据集下载项目正是一个为研究人员和开发者提供便捷数据集获取途径的宝藏。该项目提供了coco128-seg数据集的压缩文件下载,这是一个用于图像分割的公开数据集,包含了128种不同的物体类别,以及丰富的图像和对应的分割标注信息。

原文链接:https://blog.csdn.net/gitblog_06767/article/details/148095172

Coco128-Seg数据集下载:Coco128-Seg 数据集是一个专为图像分割任务设计的公开数据集,包含了丰富的图像及其对应的分割标注信息。该数据集以压缩文件形式提供,方便下载与使用,适用于图像分割算法的研究与应用开发。下载后,只需解压即可获取图像文件与分割标注文件,助您快速开展相关实验。使用前请确保有足够的存储空间,并遵守相关法律法规,合理使用数据集。Coco128-Seg 为图像分割领域的研究者提供了高质量的标注数据,助力算法优化与创新。 - AtomGit | GitCodehttps://gitcode.com/Premium-Resources/1d51a/?utm_source=article_gitcode_universal&index=bottom&type=card&&uuid_tt_dd=11_89465207772-1735818214370-445443&isLogin=1&from_id=148095172&from_link=f47418c6470e35241eafc74acf1b88c9

annotator.py yolo提供的自动给标注的

ultralytics\data\annotator.py
介绍的原文链接:https://blog.csdn.net/m0_58169876/article/details/145659508

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐