使用YOLOv8来训练——心胸肺CT检测数据集,并使用训练好的模型进行预测。
发布时间
阅读量:
阅读量


具体说明如何利用YOLOv8这一工具对包含约4100张心脏与胸部影像的心脏及胸部相关CT检测数据集进行系统性训练,并完整提供相应的训练代码及操作指南。
数据集描述
该数据集包含以下信息:
- 样本规模:4100幅图像
- 分类:12类
- 渗透入
- 瘢痕
- 间质性肺病
- 主动脉扩张
- 胸膜增厚
- 胸腔积液
- 钙化
- 心脏扩大
• 结节/肿块
• 肺不张
• 实变
• 气胸
- 分类:12类
数据集组织
假设你的数据集目录结构如下:
chest_ct_dataset/
├── train/
│ ├── images/
│ └── labels/
├── valid/
│ ├── images/
│ └── labels/
└── data.yaml # 数据配置文件
其中:
train/该目录下存储了训练数据及其对应的标签文件。valid/该目录下存储了验证数据及其对应的标签文件。data.yaml该配置文件记录了系统所需的数据参数设置。
数据配置文件
创建或确认data.yaml文件是否正确配置了数据集路径和类别信息:
train: ./train/images/ # 训练集图像路径
val: ./valid/images/ # 验证集图像路径
test: ./test/images/ # 测试集图像路径(如果有)
# Classes
nc: 12 # 类别数量
names: ['infiltrate', 'scarring', 'ild', 'aortic_enlargement',
'pleural_thickening', 'pleural_effusion', 'calcification',
'cardiomegaly', 'nodule_mass', 'atelectasis',
'consolidation', 'pneumothorax'] # 类别名称列表
VOC格式转YOLO格式
若你的数据集中包含VOC格式的标签文件,则必须将其转换为YOLO格式的TXT文件。此操作可借助提供的Python脚本完成。
import os
import xml.etree.ElementTree as ET
from PIL import Image
def convert_voc_to_yolo(xml_file, img_size, class_names, output_file):
tree = ET.parse(xml_file)
root = tree.getroot()
width = int(root.find('size/width').text)
height = int(root.find('size/height').text)
labels = []
for obj in root.iter('object'):
cls = obj.find('name').text.lower() # 将类别名转换为小写
if cls not in class_names:
continue
cls_id = class_names.index(cls)
xmlbox = obj.find('bndbox')
b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text),
float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text))
bb = convert_coordinates(b, width, height, img_size)
labels.append([cls_id, *bb])
with open(output_file, 'w') as f:
for label in labels:
f.write('%d %.6f %.6f %.6f %.6f\n' % tuple(label))
def convert_coordinates(box, orig_w, orig_h, target_size):
dw, dh = target_size
x_center = ((box[1] + box[0]) / 2) / orig_w
y_center = ((box[3] + box[2]) / 2) / orig_h
w = (box[1] - box[0]) / orig_w
h = (box[3] - box[2]) / orig_h
x_center *= dw
y_center *= dh
w *= dw
h *= dh
return x_center, y_center, w, h
def main():
class_names = ['infiltrate', 'scarring', 'ild', 'aortic_enlargement',
'pleural_thickening', 'pleural_effusion', 'calcification',
'cardiomegaly', 'nodule_mass', 'atelectasis',
'consolidation', 'pneumothorax'] # 替换为实际类别名称
img_size = (640, 640) # 输入图像大小
for phase in ['train', 'valid']:
xml_dir = f'./chest_ct_dataset/{phase}/annotations/'
txt_dir = f'./chest_ct_dataset/{phase}/labels_txt/'
os.makedirs(txt_dir, exist_ok=True)
for xml_file in os.listdir(xml_dir):
if xml_file.endswith('.xml'):
img_file = xml_file.replace('.xml', '.jpg')
img_path = os.path.join(f'./chest_ct_dataset/{phase}/images/', img_file)
img = Image.open(img_path)
img_width, img_height = img.size
output_file = os.path.join(txt_dir, img_file.replace('.jpg', '.txt'))
convert_voc_to_yolo(os.path.join(xml_dir, xml_file), img_size, class_names, output_file)
if __name__ == '__main__':
main()
执行前述脚本后,在指定路径下的train和valid目录下会创建YOLO格式的.txt标签文件
安装YOLOv8
如果你还没有安装YOLOv8,可以使用以下命令安装:
pip install ultralytics
训练模型
在YOLOv8框架下进行模型训练的指令相对便捷,在线即可完成部署操作;建议您可以直接运行以下指令启动模型训练过程:
cd path/to/chest_ct_dataset/
# 下载预训练权重
wget https://github.com/ultralytics/ultralytics/releases/download/v8.0.19/yolov8n.pt
# 开始训练
ultralytics train model=yolov8n.yaml data=./data.yaml epochs=100 imgsz=640
在这个命令中:
model=yolov8n.yaml:指定使用的YOLOv8模型配置文件。data=./data.yaml:指定数据集路径。epochs=100:设置训练轮数为100次。imgsz=640:设定输入图像尺寸为640像素。
使用预定义配置
YOLOv8包含一系列预先设置好的模型架构,包括yolov8n, yolov8s, yolov8m, yolov8l及yolov8x等不同级别的配置选项。建议根据具体需求选择相应的模型架构进行训练,并根据实际应用场景灵活调整参数设置以优化性能表现。
ultralytics train model=yolov8s.yaml data=./data.yaml epochs=100 imgsz=640
模型评估
训练完成后,可以使用以下命令评估模型在验证集上的表现:
ultralytics val model=best.pt data=./data.yaml imgsz=640
这里的best.pt是训练过程中产生的最佳模型权重文件。
模型预测
你可以使用训练好的模型对新图像进行预测:
ultralytics predict model=best.pt source=path/to/your/image.jpg imgsz=640
查看训练结果
训练过程中的记录信息会在runs/detect/目录中被存储,并且你可以访问这些信息以了解训练过程中的损失值、精度指标等数据。
注意事项
- 数据集质量:保证数据集的质量要素包含清晰度与标注准确性两方面。
- 模型选择:建议采用更高性能的模型版本(例如YOLOv8m、YOLOv8l等)以提升检测效果。
- 超参数调整:建议根据具体场景优化超参数设置包括批量大小(
batch-size)、图像尺寸(imgsz)等。 - 监控性能:在训练过程中持续跟踪损失函数值及平均精度指标(mAP),以确保模型收敛状态。
按照以下流程所述的步骤,请建议采用预训练好的YOLOv8模型来生成心胸肺CT检测相关数据集,并完成预测操作。
全部评论 (0)
还没有任何评论哟~
