使用YOLOv8来训练一个包含超过26000张遥感影像的油罐检测数据集。这个数据集包含5个类别,已标注为VOC格式,可以直接用于模型训练。
遥感影像各类油罐检测,共分为外浮顶油罐,封闭顶油罐,球形压力罐,水塔,沉淀罐五种类型,超过26000张影像,采用voc格式标注,512×215尺寸,2GB
遥感影像各类油罐检测,共分为外浮顶油罐,封闭顶油罐,球形压力罐,水塔,沉淀罐五种类型,超过26000张影像,采用voc格式标注,512×215尺寸,2GB

使用YOLOv8来训练一个包含超过26000张遥感影像的油罐检测数据集。这个数据集包含5个类别,已标注为VOC格式,可以直接用于模型训练。
数据集描述
数据量:超过26000张影像
类别:
0: 外浮顶油罐(External Floating Roof Tank)
1: 封闭顶油罐(Fixed Roof Tank)
2: 球形压力罐(Spherical Pressure Tank)
3: 水塔(Water Tower)
4: 沉淀罐(Settling Tank)
标注格式:VOC格式
图像尺寸:512×215
数据大小:约2GB
应用场景:遥感影像油罐检测
数据集组织
假设你的数据集目录结构如下:
深色版本
oil_tank_dataset/
├── images/
│ ├── 000001.jpg
│ ├── 000002.jpg
│ └── …
├── annotations/
│ ├── 000001.xml
│ ├── 000002.xml
│ └── …
└── data.yaml # 数据配置文件
数据配置文件
创建或确认data.yaml文件是否正确配置了数据集路径和类别信息:
yaml
深色版本
train: ./images/train/ # 训练集图像路径
val: ./images/val/ # 验证集图像路径
test: ./images/test/ # 测试集图像路径
Classes
nc: 5 # 类别数量
names:
- External Floating Roof Tank
- Fixed Roof Tank
- Spherical Pressure Tank
- Water Tower
- Settling Tank # 类别名称列表
数据集划分
将数据集划分为训练集、验证集和测试集。可以使用以下脚本:
python
深色版本
import os
import random
from shutil import copyfile
定义源目录和目标目录
source_images_dir = ‘./oil_tank_dataset/images’
source_annotations_dir = ‘./oil_tank_dataset/annotations’
target_train_dir = ‘./oil_tank_dataset/images/train’
target_val_dir = ‘./oil_tank_dataset/images/val’
target_test_dir = ‘./oil_tank_dataset/images/test’
target_train_annotations_dir = ‘./oil_tank_dataset/annotations/train’
target_val_annotations_dir = ‘./oil_tank_dataset/annotations/val’
target_test_annotations_dir = ‘./oil_tank_dataset/annotations/test’
创建目标目录
os.makedirs(target_train_dir, exist_ok=True)
os.makedirs(target_val_dir, exist_ok=True)
os.makedirs(target_test_dir, exist_ok=True)
os.makedirs(target_train_annotations_dir, exist_ok=True)
os.makedirs(target_val_annotations_dir, exist_ok=True)
os.makedirs(target_test_annotations_dir, exist_ok=True)
获取所有图像文件
all_images = [f for f in os.listdir(source_images_dir) if f.endswith(‘.jpg’)]
random.shuffle(all_images)
划分数据集
train_ratio = 0.8
val_ratio = 0.1
test_ratio = 0.1
train_split = int(train_ratio * len(all_images))
val_split = train_split + int(val_ratio * len(all_images))
train_images = all_images[:train_split]
val_images = all_images[train_split:val_split]
test_images = all_images[val_split:]
复制图像文件和对应的标注文件
def copy_files(image_list, target_image_dir, target_annotation_dir):
for img in image_list:
copyfile(os.path.join(source_images_dir, img), os.path.join(target_image_dir, img))
annotation = img.replace(‘.jpg’, ‘.xml’)
copyfile(os.path.join(source_annotations_dir, annotation), os.path.join(target_annotation_dir, annotation))
copy_files(train_images, target_train_dir, target_train_annotations_dir)
copy_files(val_images, target_val_dir, target_val_annotations_dir)
copy_files(test_images, target_test_dir, target_test_annotations_dir)
转换VOC标注为YOLO格式
首先,我们需要将VOC格式的标注文件转换为YOLO格式。可以使用Python脚本来完成这个任务。
python
深色版本
import os
import xml.etree.ElementTree as ET
import shutil
定义类别映射
class_map = {
‘External Floating Roof Tank’: 0,
‘Fixed Roof Tank’: 1,
‘Spherical Pressure Tank’: 2,
‘Water Tower’: 3,
‘Settling Tank’: 4
}
定义转换函数
def convert_voc_to_yolo(voc_file, yolo_file, image_size, class_map):
tree = ET.parse(voc_file)
root = tree.getroot()
with open(yolo_file, 'w') as f:
for obj in root.findall('object'):
class_name = obj.find('name').text
if class_name not in class_map:
continue
class_id = class_map[class_name]
bbox = obj.find('bndbox')
x_min = int(bbox.find('xmin').text)
y_min = int(bbox.find('ymin').text)
x_max = int(bbox.find('xmax').text)
y_max = int(bbox.find('ymax').text)
x_center = (x_min + x_max) / 2.0 / image_size[0]
y_center = (y_min + y_max) / 2.0 / image_size[1]
width = (x_max - x_min) / image_size[0]
height = (y_max - y_min) / image_size[1]
f.write(f"{class_id} {x_center} {y_center} {width} {height}\n")
读取图像尺寸
def get_image_size(image_path):
from PIL import Image
with Image.open(image_path) as img:
return img.width, img.height
转换所有标注文件
def convert_all_annotations(image_dir, annotation_dir, output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for filename in os.listdir(annotation_dir):
if filename.endswith('.xml'):
image_filename = filename.replace('.xml', '.jpg')
image_path = os.path.join(image_dir, image_filename)
voc_file = os.path.join(annotation_dir, filename)
yolo_file = os.path.join(output_dir, filename.replace('.xml', '.txt'))
image_size = get_image_size(image_path)
convert_voc_to_yolo(voc_file, yolo_file, image_size, class_map)
调用转换函数
image_dir = ‘./oil_tank_dataset/images’
annotation_dir = ‘./oil_tank_dataset/annotations’
output_dir = ‘./oil_tank_dataset/labels’
convert_all_annotations(image_dir, annotation_dir, output_dir)
安装YOLOv8
如果你还没有安装YOLOv8,可以使用以下命令安装:
pip install ultralytics
训练模型
使用YOLOv8训练模型的命令非常简单,你可以直接使用以下命令开始训练:
cd path/to/oil_tank_dataset/
克隆YOLOv8仓库
git clone https://github.com/ultralytics/ultralytics.git
cd ultralytics
开始训练
python yolo.py detect train data=…/data.yaml model=yolov8n.pt epochs=100 imgsz=512 batch=16
在这个命令中:
data=…/data.yaml:指定数据配置文件。
model=yolov8n.pt:指定预训练权重,这里使用的是YOLOv8的小模型。
epochs=100:训练轮数。
imgsz=512:输入图像的宽度(高度为215,但YOLOv8通常需要正方形输入,可以考虑调整图像大小或使用其他方法处理)。
batch=16:批量大小。
模型评估
训练完成后,可以使用以下命令评估模型在验证集上的表现:
python yolo.py detect val data=…/data.yaml model=runs/detect/train/weights/best.pt imgsz=512
这里的runs/detect/train/weights/best.pt是训练过程中产生的最佳模型权重文件。
模型预测
你可以使用训练好的模型对新图像进行预测:
python yolo.py detect predict source=path/to/your/image.jpg model=runs/detect/train/weights/best.pt imgsz=512 conf=0.4 iou=0.5
查看训练结果
训练过程中的日志和结果会保存在runs/detect/目录下,你可以查看训练过程中的损失、精度等信息。
数据增强
为了进一步提高模型性能,可以使用数据增强技术。以下是一个简单的数据增强示例:
安装albumentations库:
pip install -U albumentations
在yolo.py中添加数据增强:
p
import albumentations as A
from albumentations.pytorch import ToTensorV2
import cv2
定义数据增强
transform = A.Compose([
A.RandomSizedCrop(min_max_height=(400, 512), height=512, width=512, p=0.5),
A.HorizontalFlip(p=0.5),
A.VerticalFlip(p=0.5),
A.Rotate(limit=10, p=0.5, border_mode=cv2.BORDER_CONSTANT),
A.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.2, p=0.5),
A.GaussNoise(var_limit=(10.0, 50.0), p=0.5),
A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
ToTensorV2()
], bbox_params=A.BboxParams(format=‘yolo’, label_fields=[‘class_labels’]))
在数据加载器中应用数据增强
def collate_fn(batch):
images, targets = zip(*batch)
transformed_images = []
transformed_targets = []
for img, target in zip(images, targets):
bboxes = target['bboxes']
class_labels = target['labels']
augmented = transform(image=img, bboxes=bboxes, class_labels=class_labels)
transformed_images.append(augmented['image'])
transformed_targets.append({
'bboxes': augmented['bboxes'],
'labels': augmented['class_labels']
})
return torch.stack(transformed_images), transformed_targets
注意事项
数据集质量:确保数据集的质量,包括清晰度、标注准确性等。
模型选择:可以选择更强大的模型版本(如YOLOv8m、YOLOv8l等)以提高性能。
超参数调整:根据实际情况调整超参数,如批量大小(batch)、图像大小(imgsz)等。
监控性能:训练过程中监控损失函数和mAP指标,确保模型收敛。
通过上述步骤,你可以使用YOLOv8来训练一个遥感影像油罐检测数据集,并使用训练好的模型进行预测。
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐

所有评论(0)