深度学习目标检测中如何使用YOLO系列算法来训练McShips船舶数据集模型 识别民用船舶及军舰的检测
McShips船舶数据集,标签为xml文件格式,可用于yolo系列算法,旨在进行船舶检测和细粒度分类。
。7996张图像,两类标签.民用船舶"civilianship"和军舰"warship"。
每个图像都用边界框和船级标签仔细注释。由于以下两个原因,数据集具有挑战性:首先,由于船舶具有非常相似的船型,因此船级之间的差异很小;其次,由于视点变化、天气条件变化、光照变化、尺度变化、遮挡、背景杂乱等因素,同一船级内的船舶可能存在很大的差异。
1
1
利用McShips船舶数据集进行船舶检测和细粒度分类,使用YOLO系列算法(例如YOLOv5或YOLOv8)来训练模型。XML文件格式,XML标签转换为YOLO所需的格式。介绍如何准备数据、训练模型、评估性能以及一些优化策略。
以下文字及代码仅供参考。
数据准备
1. XML到YOLO格式的转换
假设每个XML文件包含一个或多个边界框及其对应的类别信息,我们需要编写一个脚本来将这些信息转换为YOLO格式。YOLO格式要求每行代表一个对象,格式如下:
class_id center_x center_y width height
所有值都是相对于图像尺寸归一化后的浮点数。
下面是一个简单的Python脚本示例,用于执行此转换:
import os
import xml.etree.ElementTree as ET
def convert(size, box):
dw = 1./(size[0])
dh = 1./(size[1])
x = (box[0] + box[1])/2.0 - 1
y = (box[2] + box[3])/2.0 - 1
w = box[1] - box[0]
h = box[3] - box[2]
x = x*dw
w = w*dw
y = y*dh
h = h*dh
return (x,y,w,h)
def convert_annotation(xml_file_path, output_dir, classes):
tree = ET.parse(xml_file_path)
root = tree.getroot()
size = root.find('size')
w = int(size.find('width').text)
h = int(size.find('height').text)
image_name = os.path.basename(xml_file_path).replace('.xml', '.jpg')
out_file = open(os.path.join(output_dir, image_name.replace('.jpg', '.txt')), 'w')
for obj in root.iter('object'):
difficult = obj.find('difficult').text
cls = obj.find('name').text
if cls not in classes or int(difficult) == 1:
continue
cls_id = classes.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((w,h), b)
out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
# 示例调用
classes = ['civilianship', 'warship']
for xml_file in os.listdir('path_to_xml_labels'):
if xml_file.endswith('.xml'):
convert_annotation(os.path.join('path_to_xml_labels', xml_file), 'path_to_output_labels', classes)
2. 创建YOLO配置文件
创建一个data.yaml
文件,定义数据集路径和类别信息:
train: ./images/train/
val: ./images/val/
nc: 2 # 类别数量
names: ['civilianship', 'warship'] # 类别名
确保你的数据集按照以下结构组织:
dataset/
├── images/
│ ├── train/
│ └── val/
└── labels/
├── train/
└── val/
模型训练
使用YOLOv5或YOLOv8进行模型训练。这里以YOLOv5为例:
from ultralytics import YOLO
def main_train():
model = YOLO('yolov5s.pt') # 或者选择其他预训练模型
results = model.train(
data='./path/to/data.yaml',
epochs=300,
imgsz=640,
batch=16,
project='./runs/detect',
name='ship_detection',
optimizer='SGD',
device='0',
save=True,
cache=True,
)
if __name__ == '__main__':
main_train()
模型评估与优化
在训练完成后,可以通过验证集评估模型性能,并根据需要调整超参数或采用模型优化技术如混合精度训练、剪枝等。
推理与可视化
加载训练好的模型进行推理并可视化结果:
from ultralytics import YOLO
import cv2
from PIL import Image
model = YOLO('./runs/detect/ship_detection/weights/best.pt')
def detect_ship(image_path):
results = model.predict(source=image_path)
img = cv2.imread(image_path)
for result in results:
boxes = result.boxes.numpy()
for box in boxes:
r = box.xyxy
x1, y1, x2, y2 = int(r[0]), int(r[1]), int(r[2]), int(r[3])
label = result.names[int(box.cls)]
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2) # 绘制矩形框
cv2.putText(img, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
return img
# 示例调用
result_image = detect_ship('your_test_image.jpg')
Image.fromarray(cv2.cvtColor(result_image, cv2.COLOR_BGR2RGB)).show() # 使用PIL显示图像
通过上述步骤,您可以有效地使用McShips船舶数据集进行船舶检测和细粒度分类任务-