0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
会员中心
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

基于YOLOv8的自定义医学图像分割

新机器视觉 来源:新机器视觉 2023-12-20 10:51 次阅读
加入交流群
微信小助手二维码

扫码添加小助手

加入工程师交流群

YOLOv8是一种令人惊叹的分割模型;它易于训练、测试和部署。在本教程中,我们将学习如何在自定义数据集上使用YOLOv8。但在此之前,我想告诉你为什么在存在其他优秀的分割模型时应该使用YOLOv8呢?

我正在从事与医学图像分割相关的项目,当我的合作者突然告诉我,我们只有来自175名患者的600张图像和标注。在医学成像领域,这是一个常见的问题,因为临床医生是最忙碌的人,他们有许多职责。然而,他向我保证,一旦模型训练好(并进行微调),我们将获得来自其他300多名患者的图像和标注,作为额外的测试集以评估我们的模型。

我开始将这50名患者分为训练、测试和验证数据集,使用8010的比例。对于模型,我首先尝试了UNet及其变体(ResUNet、Attention UNet、Res-Attention UNet)。这些模型在训练、测试和验证数据集上表现出色,但在额外的测试集上表现糟糕。然后我想,“让我们试试YOLOv8;如果有效,那将是很好的,如果不行,那将是一次有趣的学习经历。”几个小时后,它奏效了,令我惊讶的是,在额外的测试集上远远超出了我的预期。我不能透露具体数值,因为论文仍在审查中,但我愿意分享如何将其调整为自定义数据集,以便你可以节省大量工作时间。让我们开始制定攻略。

攻略

以下是我们将学习的主题:

1. YOLOv8简介

2. 安装库

3. 数据集准备

4. 训练准备

5. 训练模型

6. 结果

YOLOv8简介

YOLOv8是YOLO系列的最新版本,用于实时目标检测,由Ultralytics开发。它通过引入空间注意力和特征融合等修改来提高准确性和速度。该架构将修改过的CSPDarknet53骨干网络与用于处理的先进头部相结合。这些先进之处使YOLOv8成为各种计算机视觉任务的最新选择。

安装库

以下是安装库的选项。

# Install the ultralytics package using conda
conda install -c conda-forge ultralytics


or 


# Install the ultralytics package from PyPI
pip install ultralytics

数据集准备

数据集需要进行两个步骤的处理:

步骤1:请按照以下结构组织您的数据集(图像和掩膜):理想情况下,训练、测试和验证(val)的比例为8010。数据集文件夹的安排如下:

dataset
|
|---train
|   |-- images
|   |-- labels 
|   
|---Val
|   |-- images 
|   |-- labels
|
|---test
|   |-- images
|   |-- labels

步骤2:第二步是将 .png(或任何类型)掩膜(标签)转换为所有3个标签文件夹中的 .txt 文件。以下是将标签(.png、.jpg)转换为 .txt 文件的Python代码。(您也可以在此操作)

将每个标签图像转换为 .txt 文件

import numpy as np
from PIL import Image


import numpy as np
from PIL import Image
from pathlib import Path


def create_label(image_path, label_path):
    # Load the image from the given path and convert it to a NumPy array
    mask = np.asarray(Image.open(image_path))


    # Find the coordinates of non-zero (i.e., not black) pixels in the mask's first channel (assumed to be red)
    rows, cols = np.nonzero(mask[:, :, 0])


    # If no non-zero pixels are found in the mask, return early as there's nothing to label
    if len(rows) == 0:
        return  # Optionally, handle the case of no non-zero pixels as needed


    # Calculate the normalized coordinates by dividing by the respective dimensions of the image
    # This is done to ensure that the coordinates are relative (between 0 and 1) rather than absolute
    normalized_coords = [(col / mask.shape[1], row / mask.shape[0]) for row, col in zip(rows, cols)]


    # Construct a string representing the label data
    # The format starts with '0' (which might represent a class id or similar) followed by pairs of normalized coordinates
    label_line = '0 ' + ' '.join([f'{cord[0]} {cord[1]}' for cord in normalized_coords])


    # Ensure that the directory for the label_path exists, create it if not
    Path(label_path).parent.mkdir(parents=True, exist_ok=True)


    # Open the label file in write mode and write the label_line to it
    with open(label_path, 'w') as f:
        f.write(label_line)






import os


for x in ['train', 'val', 'test']:
    images_dir_path = Path(f'datasets/{x}/labels')
    for img_path in images_dir_path.iterdir():
        if img_path.is_file() and img_path.suffix.lower() in ['.jpg', '.jpeg', '.png', '.bmp']:
            label_path = img_path.parent.parent / 'labels_' / f'{img_path.stem}.txt'
            label_line = create_label(img_path, label_path)
        else:
            print(f"Skipping non-image file: {img_path}")

请注意:在运行上述代码后,请不要忘记从标签文件夹中删除标签(掩膜)图像。

训练准备

为训练创建 'data.yaml' 文件。只需在Python中运行下面的代码,它将为YOLOv8创建 'data.yaml' 文件。

yaml_content = f'''
train: train/images
val: val/images
test: test/images


names: ['object']
# Hyperparameters ------------------------------------------------------------------------------------------------------
# lr0: 0.01  # initial learning rate (i.e. SGD=1E-2, Adam=1E-3)
# lrf: 0.01  # final learning rate (lr0 * lrf)
# momentum: 0.937  # SGD momentum/Adam beta1
# weight_decay: 0.0005  # optimizer weight decay 5e-4
# warmup_epochs: 3.0  # warmup epochs (fractions ok)
# warmup_momentum: 0.8  # warmup initial momentum
# warmup_bias_lr: 0.1  # warmup initial bias lr
# box: 7.5  # box loss gain
# cls: 0.5  # cls loss gain (scale with pixels)
# dfl: 1.5  # dfl loss gain
# pose: 12.0  # pose loss gain
# kobj: 1.0  # keypoint obj loss gain
# label_smoothing: 0.0  # label smoothing (fraction)
# nbs: 64  # nominal batch size
# hsv_h: 0.015  # image HSV-Hue augmentation (fraction)
# hsv_s: 0.7  # image HSV-Saturation augmentation (fraction)
# hsv_v: 0.4  # image HSV-Value augmentation (fraction)
degrees: 0.5  # image rotation (+/- deg)
translate: 0.1  # image translation (+/- fraction)
scale: 0.2  # image scale (+/- gain)
shear: 0.2  # image shear (+/- deg) from -0.5 to 0.5
perspective: 0.1  # image perspective (+/- fraction), range 0-0.001
flipud: 0.7  # image flip up-down (probability)
fliplr: 0.5  # image flip left-right (probability)
mosaic: 0.8  # image mosaic (probability)
mixup: 0.1  # image mixup (probability)
# copy_paste: 0.0  # segment copy-paste (probability)
    '''
    
with Path('data.yaml').open('w') as f:
    f.write(yaml_content)

训练模型

一旦数据准备好,其余的非常简单,只需运行以下代码。

import matplotlib.pyplot as plt
from ultralytics import YOLO


model = YOLO("yolov8n-seg.pt")


results = model.train(
        batch=8,
        device="cpu",
        data="data.yaml",
        epochs=100,
        imgsz=255)

d2faa654-9eda-11ee-8b88-92fbcf53809c.jpg

恭喜,你成功了。现在你会看到一个 'runs' 文件夹,你可以在其中找到所有的训练矩阵和图表。

结果

好,让我们在测试数据上检查结果:

model = YOLO("runs/segment/train13/weights/best.pt") # load the model


file = glob.glob('datasets/test/images/*') # let's get the images

现在让我们在图像上运行代码。

# lets run the model over every image
for i in range(len(file)):
    result = model(file[i], save=True, save_txt=True)

将每个 Pred.txt 文件转换为 mask.png

import numpy as np
import cv2


def convert_label_to_image(label_path, image_path):
    # Read the .txt label file
    with open(label_path, 'r') as f:
        label_line = f.readline()


    # Parse the label line to extract the normalized coordinates
    coords = label_line.strip().split()[1:]  # Remove the class label (assuming it's always 0)


    # Convert normalized coordinates to pixel coordinates
    width, height = 256, 256  # Set the dimensions of the output image
    coordinates = [(float(coords[i]) * width, float(coords[i+1]) * height) for i in range(0, len(coords), 2)]
    coordinates = np.array(coordinates, dtype=np.int32)


    # Create a blank image
    image = np.zeros((height, width, 3), dtype=np.uint8)


    # Draw the polygon using the coordinates
    cv2.fillPoly(image, [coordinates], (255, 255, 255))  # Fill the polygon with white color
    print(image.shape)
    # Save the image
    cv2.imwrite(image_path, image)
    print("Image saved successfully.")


# Example usage
label_path = 'runs/segment/predict4/val_labels/img_105.txt'
image_path = 'runs/segment/predict4/val_labels/img_105.jpg'
convert_label_to_image(label_path, image_path)






file = glob.glob('runs/segment/predict11/labels/*.txt')
for i in range(len(file)):
    label_path = file[i]
    image_path = file[i][:-3]+'jpg'
    convert_label_to_image(label_path, image_path)
审核编辑:汤梓红
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 模型
    +关注

    关注

    1

    文章

    3648

    浏览量

    51692
  • 数据集
    +关注

    关注

    4

    文章

    1230

    浏览量

    26034
  • 医学图像分割

    关注

    0

    文章

    5

    浏览量

    927

原文标题:基于YOLOv8的自定义医学图像分割

文章出处:【微信号:vision263com,微信公众号:新机器视觉】欢迎添加关注!文章转载请注明出处。

收藏 人收藏
加入交流群
微信小助手二维码

扫码添加小助手

加入工程师交流群

    评论

    相关推荐
    热点推荐

    基于YOLOv8实现自定义姿态评估模型训练

    Hello大家好,今天给大家分享一下如何基于YOLOv8姿态评估模型,实现在自定义数据集上,完成自定义姿态评估模型的训练与推理。
    的头像 发表于 12-25 11:29 5537次阅读
    基于<b class='flag-5'>YOLOv8</b>实现<b class='flag-5'>自定义</b>姿态评估模型训练

    labview调用yolov8/11目标检测、分割、分类

    labview使用2020版本64位编辑,调用yolov8/11的onnx模型案例。 源码: 通过网盘分享的文件:Labview_cls.zip等4个文件 链接: https
    发表于 04-21 19:37

    如何修改yolov8分割程序中的kmodel?

    自定义YOLOv8分割类class SegmentationApp(AIBase): def __init__(self,kmodel_path,labels,model_input_size
    发表于 04-25 08:22

    使用YOLOv8做目标检测和实例分割的演示

    YOLOv8是来自Ultralytics的最新的基于YOLO的对象检测模型系列,提供最先进的性能。
    的头像 发表于 02-06 10:11 8871次阅读

    YOLOv8自定义数据集训练到模型部署推理简析

    如果你只是想使用而不是开发,强烈推荐通过pip安装方式获取YOLOv8包!YOLOv8安装命令行
    的头像 发表于 03-24 09:27 1.2w次阅读

    TensorRT 8.6 C++开发环境配置与YOLOv8实例分割推理演示

    YOLOv8实例分割TensorRT 推理代码已经完成C++类封装,三行代码即可实现YOLOv8对象检测与实例分割模型推理,不需要改任何代码即可支持
    的头像 发表于 04-25 10:49 8431次阅读
    TensorRT 8.6 C++开发环境配置与<b class='flag-5'>YOLOv8</b>实例<b class='flag-5'>分割</b>推理演示

    YOLOv8版本升级支持小目标检测与高分辨率图像输入

    YOLOv8版本最近版本又更新了,除了支持姿态评估以外,通过模型结构的修改还支持了小目标检测与高分辨率图像检测。原始的YOLOv8模型结构如下。
    的头像 发表于 05-16 11:14 1.5w次阅读
    <b class='flag-5'>YOLOv8</b>版本升级支持小目标检测与高分辨率<b class='flag-5'>图像</b>输入

    在AI爱克斯开发板上用OpenVINO™加速YOLOv8-seg实例分割模型

    《在 AI 爱克斯开发板上用 OpenVINO 加速 YOLOv8 目标检测模型》介绍了在 AI 爱克斯开发板上使用 OpenVINO 开发套件部署并测评 YOLOv8 的目标检测模型,本文将介绍在 AI 爱克斯开发板上使用 OpenVINO 加速
    的头像 发表于 06-05 11:52 1768次阅读
    在AI爱克斯开发板上用OpenVINO™加速<b class='flag-5'>YOLOv8</b>-seg实例<b class='flag-5'>分割</b>模型

    教你如何用两行代码搞定YOLOv8各种模型推理

    大家好,YOLOv8 框架本身提供的API函数是可以两行代码实现 YOLOv8 模型推理,这次我把这段代码封装成了一个类,只有40行代码左右,可以同时支持YOLOv8对象检测、实例分割
    的头像 发表于 06-18 11:50 4617次阅读
    教你如何用两行代码搞定<b class='flag-5'>YOLOv8</b>各种模型推理

    如何修改YOLOv8的源码

    很多人也想跟修改YOLOv5源码一样的方式去修改YOLOv8的源码,但是在github上面却发现找到的YOLOv8项目下面TAG分支是空的,然后就直接从master/main下面把源码克隆出来一通
    的头像 发表于 09-04 10:02 3623次阅读
    如何修改<b class='flag-5'>YOLOv8</b>的源码

    用自己的数据集训练YOLOv8实例分割模型

    YOLOv8 于 2023 年 1 月 10 日推出。截至目前,这是计算机视觉领域分类、检测和分割任务的最先进模型。该模型在准确性和执行时间方面都优于所有已知模型。
    的头像 发表于 11-10 16:44 6839次阅读
    用自己的数据集训练<b class='flag-5'>YOLOv8</b>实例<b class='flag-5'>分割</b>模型

    YOLOv8实现旋转对象检测

    YOLOv8框架在在支持分类、对象检测、实例分割、姿态评估的基础上更近一步,现已经支持旋转对象检测(OBB),基于DOTA数据集,支持航拍图像的15个类别对象检测,包括车辆、船只、典型各种场地等。包含2800多张
    的头像 发表于 01-11 10:43 4013次阅读
    <b class='flag-5'>YOLOv8</b>实现旋转对象检测

    RK3576 yolov8训练部署教程

    本章展示yolov8模型的在EASY EAI Orin nano的部署过程。
    的头像 发表于 04-02 16:04 1562次阅读
    RK3576 <b class='flag-5'>yolov8</b>训练部署教程

    RV1126 yolov8训练部署教程

    YOLOv8 是 ultralytics 公司在 2023 年 1月 10 号开源的基于YOLOV5进行更新的 下一个重大更新版本,目前支持图像分类、物体检测和实例分割任务,鉴于
    的头像 发表于 04-16 14:53 1130次阅读
    RV1126 <b class='flag-5'>yolov8</b>训练部署教程

    使用ROCm™优化并部署YOLOv8模型

    作者:AVNET 李鑫杰 一,YOLOv8介绍? YOLOv8 由 Ultralytics 于 2023 年 1 月 10 日发布,在准确性和速度方面提供了前沿的性能。YOLOv8 在之前 YOLO
    的头像 发表于 09-24 18:32 504次阅读
    使用ROCm™优化并部署<b class='flag-5'>YOLOv8</b>模型