kornia目标检测/分割图像扩增

目标检测任务下图像扩增经常使用imgaug库,笔者实现了基于imgaug库的VOC格式图像数据扩增,有兴趣小伙伴可以了解一下,代码位于:

https://github.com/ouening/OD_dataset_conversion_scripts/blob/master/voc_augument.py

本博文主要介绍另一个图像处理工具新秀——kornia,在去最新版本中已经新增了augmentation接口,可以很方便地进行图像数据扩增,包括常规类型、bbox类型、segment类型和keypoint类型。

1. bbox目标检测扩增

本文主要介绍bbox形式的扩增,参考官方例子:

https://kornia-tutorials.readthedocs.io/en/latest/data_augmentation_sequential.html#install-and-get-data

主要用到的API为

AugmentationSequential(*args, data_keys=[<DataKey.INPUT: 0>], same_on_batch=None, return_transform=None, keepdim=None, random_apply=False)

Args:
    *args: a list of kornia augmentation modules.
    data_keys: the input type sequential for applying augmentations.
        Accepts "input", "mask", "bbox", "bbox_xyxy", "bbox_xywh", "keypoints".
    same_on_batch: apply the same transformation across the batch.
        If None, it will not overwrite the function-wise settings.
    return_transform: if ``True`` return the matrix describing the transformation
        applied to each. If None, it will not overwrite the function-wise settings.
    keepdim: whether to keep the output shape the same as input (True) or broadcast it
        to the batch form (False). If None, it will not overwrite the function-wise settings.
    random_apply: randomly select a sublist (order agnostic) of args to
        apply transformation.
        If int, a fixed number of transformations will be selected.
        If (a,), x number of transformations (a <= x <= len(args)) will be selected.
        If (a, b), x number of transformations (a <= x <= b) will be selected.
        If True, the whole list of args will be processed as a sequence in a random order.
        If False, the whole list of args will be processed as a sequence in original order.

注意参数data_keys该参数指定输入数据的类型,允许类型有:"input", "mask", "bbox", "bbox_xyxy", "bbox_xywh", "keypoints", 官方教程使用了一个熊猫的例子,绘制了 bbox(头部位置), maskkeypoint(眼睛位置)对应的代码为:

aug_list = AugmentationSequential(
    K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),
    K.RandomAffine(360, [0.1, 0.1], [0.7, 1.2], [30., 50.], p=1.0),
    K.RandomPerspective(0.5, p=1.0),
    data_keys=["input", "bbox", "keypoints", "mask"],
    return_transform=False,
    same_on_batch=False,
)

bbox = torch.tensor([[[355,10],[660,10],[660,250],[355,250]]])
keypoints = torch.tensor([[[465, 115], [545, 116]]])
mask = bbox_to_mask(torch.tensor([[[155,0],[900,0],[900,400],[155,400]]]), w, h).float()
plt.imshow(mask.squeeze_().numpy()); plt.show()

img_out = plot_resulting_image(img_tensor, bbox, keypoints, mask)
plt.imshow(img_out); plt.axis('off'); plt.show()

在这里插入图片描述

在这里插入图片描述

图像扩增方仿射变affine和透视变换perspective,那么原来的bbox经过变换后势必会变形,如上图红框为bbox变形后的形状。这种bbox不适用于通常的2D目标检测(二维旋转目标检测可合适,笔并未研究过,不在讨论范围之内),因此要进行转换成如上图中绿色的bbox形式。在官方例子上进行简单修改,可以得目标检测的图像扩增数据(image-bbox pair)。

转换原理:
在这里插入图片描述

转换代码(核心内容写在函数plot_resulting_image里面):

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug  7 21:22:19 2021
"""

# !wget https://tinypng.com/images/social/website.jpg -O panda.jpg

from matplotlib import pyplot as plt
import numpy as np
import torch
import cv2

from kornia import augmentation as K
from kornia.augmentation import AugmentationSequential
from kornia.geometry import bbox_to_mask
from kornia.utils import image_to_tensor, tensor_to_image
from torchvision.transforms import transforms

to_tensor = transforms.ToTensor()
to_pil = transforms.ToPILImage()

def plot_resulting_image(img, bbox, keypoints, mask):
    img = img * mask
    img_draw = cv2.polylines(np.array(to_pil(img)), bbox.numpy(), isClosed=True, color=(255, 0, 0))
    for k in keypoints[0]:
        img_draw = cv2.circle(img_draw, tuple(k.numpy()[:2]), radius=6, color=(255, 0, 0), thickness=-1)
    
    for point in bbox.squeeze().numpy():
        img_draw = cv2.circle(img_draw,point, radius=6, color=(0,0,255), thickness=-1)
        
    # find the corrected bbox
    bbox = bbox.squeeze().numpy()
    xmin, xmax = np.min(bbox[:,0]), np.max(bbox[:,0])
    ymin, ymax = np.min(bbox[:,1]), np.max(bbox[:,1])
    x1=x4=xmin
    x2=x3=xmax
    y1=y2=ymin
    y3=y4=ymax
    pts = np.array([[[x1,y1], [x2,y2], [x3,y3], [x4,y4]]]) # note: 3 dimention
    img_draw = cv2.polylines(img_draw, pts, isClosed=True, color=(0, 255, 0))
    return img_draw

img = cv2.imread("panda.jpg", cv2.IMREAD_COLOR)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
h, w = img.shape[:2]

img_tensor = image_to_tensor(img).float() / 255.
plt.imshow(img); plt.axis('off'); plt.show()
#%%
aug_list = AugmentationSequential(
    K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),
    K.RandomAffine(360, [0.1, 0.1], [0.7, 1.2], [30., 50.], p=1.0),
    K.RandomPerspective(0.5, p=1.0),
    data_keys=["input", "bbox", "keypoints", "mask"],
    return_transform=False,
    same_on_batch=False,
)

bbox = torch.tensor([[[355,10],[660,10],[660,250],[355,250]]])
keypoints = torch.tensor([[[465, 115], [545, 116]]])
mask = bbox_to_mask(torch.tensor([[[155,0],[900,0],[900,400],[155,400]]]), w, h).float()
plt.imshow(mask.squeeze_().numpy()); plt.show()

img_out = plot_resulting_image(img_tensor, bbox, keypoints, mask)
plt.imshow(img_out); plt.axis('off'); plt.show()

#%%
out_tensor = aug_list(img_tensor, bbox.float(), keypoints.float(), mask)
img_out = plot_resulting_image(
    out_tensor[0][0],
    out_tensor[1].int(),
    out_tensor[2].int(),
    out_tensor[3][0],
)
plt.imshow(img_out); plt.axis('off'); plt.show()
#%%
out_tensor_inv = aug_list.inverse(*out_tensor)
img_out = plot_resulting_image(
    out_tensor_inv[0][0],
    out_tensor_inv[1].int(),
    out_tensor_inv[2].int(),
    out_tensor_inv[3][0],
)
plt.imshow(img_out); plt.axis('off'); plt.show()

结果的话前面已经展示了,这里就不在放出。

2. 图像分割数据扩增

官方例子:

!wget http://www.zemris.fer.hr/~ssegvic/multiclod/images/causevic16semseg3.png
import matplotlib.pyplot as plt
import cv2
import numpy as np

import torch
import torch.nn as nn
import kornia as K

# 继承torch.nn.Module
class MyAugmentation(nn.Module):
  def __init__(self):
    super(MyAugmentation, self).__init__()
    # we define and cache our operators as class members
    self.k1 = K.augmentation.ColorJitter(0.15, 0.25, 0.25, 0.25)
    self.k2 = K.augmentation.RandomAffine([-45., 45.], [0., 0.15], [0.5, 1.5], [0., 0.15])
    self.k3 = K.augmentation.RandomPerspective(0.5, p=1.0)

  def forward(self, img: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
    # 1. apply color only in image
    # 2. apply geometric tranform
    img_out = self.k3(self.k2(self.k1(img)))

    # 3. infer geometry params to mask
    # TODO: this will change in future so that no need to infer params
    mask_out = self.k3(self.k2(mask, self.k2._params), self.k3._params)

    return img_out, mask_out

def load_data(data_path: str) -> torch.Tensor:
  data: np.ndarray = cv2.imread(data_path, cv2.IMREAD_COLOR)
  data_t: torch.Tensor = K.image_to_tensor(data, keepdim=False)
  data_t = K.bgr_to_rgb(data_t)
  data_t = K.normalize(data_t, torch.tensor([0.]), torch.tensor([255.]))
  img, labels = data_t[..., :571], data_t[..., 572:]
  return img, labels

# load data (B, C, H, W)
img, labels = load_data("causevic16semseg3.png")

# create augmentation instance
aug = MyAugmentation()

# apply the augmenation pipelone to our batch of data
img_aug, labels_aug = aug(img, labels)

# visualize
img_out = torch.cat([img, labels], dim=-1)
plt.imshow(K.tensor_to_image(img_out))
plt.axis('off')

# generate several samples
num_samples: int = 10

for img_id in range(num_samples):
  # generate data
  img_aug, labels_aug = aug(img, labels)
  img_out = torch.cat([img_aug, labels_aug], dim=-1)

  # save data
  plt.figure()
  plt.imshow(K.tensor_to_image(img_out))
  plt.axis('off')
  plt.savefig(f"img_{img_id}.png", bbox_inches='tight')

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 目标检测是计算机视觉领域的一个重要研究方向。在现实生活中,很多场景都需要进行目标检测,如自动驾驶、视频监控等。TXT数据扩增是一种数据增强的方法,可以有效提高目标检测的准确率。 TXT数据扩增的方法主要有以下几种:平移、旋转、缩放、翻转等。其中,平移是指将图像在水平和垂直方向上移动一定的像素,旋转是指将图像按照一定的角度进行旋转,缩放是指对图像的大小进行缩放,翻转是指将图像水平或垂直方向上进行翻转。 对于目标检测来说,TXT数据扩增可以帮助模型更好地识别目标。例如,在物体检测中,物体的位置可能会因为光照、风吹偏移等因素而发生变化,而使用平移、旋转、缩放、翻转等操作可以模拟这些变化,从而提高模型的适应性和鲁棒性。 在实际应用中,TXT数据扩增可以结合深度学习进行,通过增加数据集来提高模型的泛化能力,从而使模型在检测目标时更加准确、稳定、鲁棒。同时,为了提高扩增图像的质量,还可以对图像进行去噪、锐化等操作,以使最终的图像质量更加清晰、锐利。 综上所述,TXT数据扩增是一种有效的数据增强方法,可以提高目标检测的准确率和鲁棒性。在实际应用中,常常需要结合不同的方法来进行数据扩增,以使模型更好地适应不同的场景和问题。 ### 回答2: 目标检测是计算机视觉中的一项重要任务,其核心是对图像中的物体进行检测和识别。在目标检测的过程中,数据集的质量和数量决定了模型的准确性和泛化能力。因此,数据扩增是提高模型性能的重要手段之一。 在目标检测中,常用的数据扩增方式包括图像旋转、缩放、裁剪、镜像等操作。扩增的目的是增加原始数据集的多样性,同时保持物体的几何形态和视觉特征不变。 针对txt数据的扩增,可以通过以下方式实现。首先,读取原始txt文件,将其中包含的物体位置信息和类别标签提取出来。然后,通过图像处理库或自定义函数进行数据扩增,如图像旋转、缩放、裁剪、镜像等操作。在扩增过程中,需要保证物体位置信息和类别标签的一致性和准确性。最后,生成新的扩增后的txt文件,保存在预定义的路径下,以便后续训练使用。 综上所述,目标检测的txt数据扩增是提高模型性能的关键步骤之一。通过扩增数据集,可以增加数据的多样性,提高模型的泛化能力和准确性,从而更好地适应实际场景中的物体检测任务。 ### 回答3: 目标检测是一种计算机视觉技术,它可以自动识别图像或视频中的对象并将其分类。txt数据扩增是指利用一系列数据增强技术扩充txt格式的标注文件,以增加训练数据量,从而提高目标检测算法的精度和鲁棒性。 txt数据扩增的常用方法包括剪切、旋转、镜像、缩放、色彩变换以及添加噪声等。这些方法都可以通过数据增强库来实现,如OpenCV、imgaug等。 剪切是将原图像中的一部分进行裁剪,以产生具有不同纵横比例的图像,从而增加训练样本的多样性。旋转可以对原图像进行不同角度的旋转,使得目标检测算法对目标的不同朝向具有更好的识别能力。镜像则是将原图像翻转,以产生关于中心对称的图像。缩放可以对原图像进行放缩,以使目标在不同尺度下具有更好的检测能力。色彩变换可以改变图像的颜色和亮度,进一步增强算法的鲁棒性。加噪声可以在图像中添加随机噪声,模拟真实环境中的不稳定因素,提高算法的应对能力。 综上所述,txt数据扩增是通过增加数据样本来提高目标检测算法的性能。采用多种数据增强技术可以有效地增加训练数据的多样性,从而提高算法的精度和鲁棒性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值