主要参考:
图像样本增广,yoloV5扩展
Albumentation库 bbox使用案例代码
【YOLOV5-5.x 源码解读】general.py
这里写目录标题
albumentation
官方文档:
https://albumentations.ai/docs/#getting-started-with-albumentations
或移步我之前的文章
标注框(真实框、bbox)格式
具体转换可以我之前的文章 基础学习 3_YOLO、VOC的数据格式转换
标注框随数据增强进行修改
关键代码:
Compose(aug, # aug为操作组合 本文中 aug=[VerticalFlip(p=1)]
augmented = aug(**annotations)
bbox_params={
'format': 'pascal_voc',
'min_area': min_area,
'min_visibility': min_visibility,
'label_fields': ['category_id']}
)
minu area
和minu visibility
参数控制图片在增强后大小发生变化时应该对增强的边界框执行的操作。如果应用空间增强(例如,裁剪图像的一部分或调整图像大小),边界框的大小可能会更改
minu area
是以像素为单位的值。如果增强后标注框的面积小于最小面积,则Albumentations将删除该框(返回的扩展边界框列表将不包含标注框)
minu visibility
是介于0和1之间的值。如果增强后的标注框面积与增强前的标注框面积之比小于最小可见性,则Albumentations将删除该框。(如果增强过程剪切了某个标注框的大部分位置,那么该框将不会出现在返回的标注框列表中)
label_fields
=[‘class_labels’, ‘class_categories’]
class_labels 一个类别中的细分,例如class_categories 是动物,class_labels 则可以是狗、猫、牛等
完整代码如下:
xywh2xyxy.py(VOC、YOLO格式转换)
这部分是从Yolov5官方开源的代码中 截取一部分出来的
import cv2
import numpy as np
import pandas as pd
import pkg_resources as pkg
import torch
import torchvision
import yaml
def clip_coords(boxes, shape):
# Clip bounding xyxy bounding boxes to image shape (height, width)
'''
将boxes的坐标(x1y1x2y2左上角右下角)限定在图像的尺寸(img_shapehw)内,防止出界。
这个函数会用在下面的xyxy2xywhn、save_one_boxd等函数中,很重要,必须掌握
'''
if isinstance(boxes, torch.Tensor): # faster individually
boxes[:, 0].clamp_(0, shape[1]) # x1
boxes[:, 1].clamp_(0, shape[0]) # y1
boxes[:, 2].clamp_(0, shape[1]) # x2
boxes[:, 3].clamp_(0, shape[0]) # y2
else: # np.array (faster grouped)
boxes[:, [0, 2]] = boxes[:, [0, 2]].clip(0, shape[1]) # x1, x2
boxes[:, [1, 3]] = boxes[:, [1, 3]].clip(0, shape[0]) # y1, y2
def xyxy2xywh(x):
# Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right
y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center
y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center
y[:, 2] = x[:, 2] - x[:, 0] # width
y[:, 3] = x[:, 3] - x[:, 1] # height
return y
def xywh2xyxy(