代码复现:Copy-Paste 数据增强for 语义分割

论文:Simple Copy-Paste is a Strong Data Augmentation Method for Instance Segmentation

非官方实现代码:https://github.com/qq995431104/Copy-Paste-for-Semantic-Segmentation

目录

一、前言

二、思路及代码


一、前言

前些天分享了一篇谷歌的数据增强论文,解读在这:https://blog.csdn.net/oYeZhou/article/details/111307717

可能由于方法比较简单,官方没有开源代码,于是,我自己尝试在语义分割数据集上进行了实现,代码见GitHub

先看下实现的效果:

原图:

 

 

使用复制-粘贴方法增强后:

将合成后的annotation和image叠加可视化出来:

 

二、思路及代码

从上面的可视化结果,可以看出,我们需要两组样本:一组image+annotation为源图,一组image+annotation为主图,我们的目的是将源图及其标注信息叠加到主图及其标注信息上;同时,需要对源图的信息做随机水平翻转、大尺度抖动/随机缩放的操作。

思路如下:

  1. 随机选取源图像I_{src}(用于提取目标)、主图像I_{main}(用于将所提取的目前粘贴在其之上);
  2. I_{src}I_{main}分别进行随机水平翻转;
  3. 根据参数设置,对I_{src}I_{main}进行大尺度抖动(Large Scale Jittering,LSJ),或者仅对I_{src}进行随机尺度缩放;
  4. I_{src}及其对应的mask_{src}分别使用公式I_{1} \times \alpha+I_{2} \times(1-\alpha)进行合成,生成合成的图像及其对应mask;
  5. 保存图像及mask,其中,mask转为8位调色板模式保存;

具体实现的代码如下(需要你的数据集为VOC格式,如果是coco格式,需要先将coco数据集的mask提取出来,可以参考这篇博客):

"""
Unofficial implementation of Copy-Paste for semantic segmentation
"""

from PIL import Image
import imgviz
import cv2
import argparse
import os
import numpy as np
import tqdm


def save_colored_mask(mask, save_path):
    lbl_pil = Image.fromarray(mask.astype(np.uint8), mode="P")
    colormap = imgviz.label_colormap()
    lbl_pil.putpalette(colormap.flatten())
    lbl_pil.save(save_path)


def random_flip_horizontal(mask, img, p=0.5):
    if np.random.random() < p:
        img = img[:, ::-1, :]
        mask = mask[:, ::-1]
    return mask, img


def img_add(img_src, img_main, mask_src):
    if len(img_main.shape) == 3:
        h, w, c = img_main.shape
    elif len(img_main.shape) == 2:
        h, w = img_main.shape
    mask = np.asarray(mask_src, dtype=np.uint8)
    sub_img01 = cv2.add(img_src, np.zeros(np.shape(img_src), dtype=np.uint8), mask=mask)
    mask_02 = cv2.resize(mask, (w, h), interpolation=cv2.INTER_NEAREST)
    mask_02 = np.asarray(mask_02, dtype=np.uint8)
    sub_img02 = cv2.add(img_main, np.zeros(np.shape(img_main), dtype=np.uint8),
                        mask=mask_02)
    img_main = img_main - sub_img02 + cv2.resize(sub_img01, (img_main.shape[1], img_main.shape[0]),
                                                 interpolation=cv2.INTER_NEAREST)
    return img_main


def rescale_src(mask_src, img_src, h, w):
    if len(mask_src.shape) == 3:
        h_src, w_src, c = mask_src.shape
    elif len(mask_src.shape) == 2:
        h_src, w_src = mask_src.shape
    max_reshape_ratio = min(h / h_src, w / w_src)
    rescale_ratio = np.random.uniform(0.2, max_reshape_ratio)

    # reshape src img and mask
    rescale_h, rescale_w = int(h_src * rescale_ratio), int(w_src * rescale_ratio)
    mask_src = cv2.resize(mask_src, (rescale_w, rescale_h),
                          interpolation=cv2.INTER_NEAREST)
    # mask_src = mask_src.resize((rescale_w, rescale_h), Image.NEAREST)
    img_src = cv2.resize(img_src, (rescale_w, rescale_h),
                         interpolation=cv2.INTER_LINEAR)

    # set paste coord
    py = int(np.random.random() * (h - rescale_h))
    px = int(np.random.random() * (w - rescale_w))

    # paste src img and mask to a zeros background
    img_pad = np.zeros((h, w, 3), dtype=np.uint8)
    mask_pad = np.zeros((h, w), dtype=np.uint8)
    img_pad[py:int(py + h_src * rescale_ratio), px:int(px + w_src * rescale_ratio), :] = img_src
    mask_pad[py:int(py + h_src * rescale_ratio), px:int(px + w_src * rescale_ratio)] = mask_src

    return mask_pad, img_pad


def Large_Scale_Jittering(mask, img, min_scale=0.1, max_scale=2.0):
    rescale_ratio = np.random.uniform(min_scale, max_scale)
    h, w, _ = img.shape

    # rescale
    h_new, w_new = int(h * rescale_ratio), int(w * rescale_ratio)
    img = cv2.resize(img, (w_new, h_new), interpolation=cv2.INTER_LINEAR)
    mask = cv2.resize(mask, (w_new, h_new), interpolation=cv2.INTER_NEAREST)
    # mask = mask.resize((w_new, h_new), Image.NEAREST)

    # crop or padding
    x, y = int(np.random.uniform(0, abs(w_new - w))), int(np.random.uniform(0, abs(h_new - h)))
    if rescale_ratio <= 1.0:  # padding
        img_pad = np.ones((h, w, 3), dtype=np.uint8) * 168
        mask_pad = np.zeros((h, w), dtype=np.uint8)
        img_pad[y:y+h_new, x:x+w_new, :] = img
        mask_pad[y:y+h_new, x:x+w_new] = mask
        return mask_pad, img_pad
    else:  # crop
        img_crop = img[y:y+h, x:x+w, :]
        mask_crop = mask[y:y+h, x:x+w]
        return mask_crop, img_crop


def copy_paste(mask_src, img_src, mask_main, img_main):
    mask_src, img_src = random_flip_horizontal(mask_src, img_src)
    mask_main, img_main = random_flip_horizontal(mask_main, img_main)

    # LSJ, Large_Scale_Jittering
    if args.lsj:
        mask_src, img_src = Large_Scale_Jittering(mask_src, img_src)
        mask_main, img_main = Large_Scale_Jittering(mask_main, img_main)
    else:
        # rescale mask_src/img_src to less than mask_main/img_main's size
        h, w, _ = img_main.shape
        mask_src, img_src = rescale_src(mask_src, img_src, h, w)

    img = img_add(img_src, img_main, mask_src)
    mask = img_add(mask_src, mask_main, mask_src)

    return mask, img


def main(args):
    # input path
    segclass = os.path.join(args.input_dir, 'SegmentationClass')
    JPEGs = os.path.join(args.input_dir, 'JPEGImages')

    # create output path
    os.makedirs(args.output_dir, exist_ok=True)
    os.makedirs(os.path.join(args.output_dir, 'SegmentationClass'), exist_ok=True)
    os.makedirs(os.path.join(args.output_dir, 'JPEGImages'), exist_ok=True)

    masks_path = os.listdir(segclass)
    tbar = tqdm.tqdm(masks_path, ncols=100)
    for mask_path in tbar:
        # get source mask and img
        mask_src = np.asarray(Image.open(os.path.join(segclass, mask_path)), dtype=np.uint8)
        img_src = cv2.imread(os.path.join(JPEGs, mask_path.replace('.png', '.jpg')))

        # random choice main mask/img
        mask_main_path = np.random.choice(masks_path)
        mask_main = np.asarray(Image.open(os.path.join(segclass, mask_main_path)), dtype=np.uint8)
        img_main = cv2.imread(os.path.join(JPEGs, mask_main_path.replace('.png', '.jpg')))

        # Copy-Paste data augmentation
        mask, img = copy_paste(mask_src, img_src, mask_main, img_main)

        mask_filename = "copy_paste_" + mask_path
        img_filename = mask_filename.replace('.png', '.jpg')
        save_colored_mask(mask, os.path.join(args.output_dir, 'SegmentationClass', mask_filename))
        cv2.imwrite(os.path.join(args.output_dir, 'JPEGImages', img_filename), img)


def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--input_dir", default="../dataset/VOCdevkit2012/VOC2012", type=str,
                        help="input annotated directory")
    parser.add_argument("--output_dir", default="../dataset/VOCdevkit2012/VOC2012_copy_paste", type=str,
                        help="output dataset directory")
    parser.add_argument("--lsj", default=True, type=bool, help="if use Large Scale Jittering")
    return parser.parse_args()


if __name__ == '__main__':
    args = get_args()
    main(args)

 

  • 9
    点赞
  • 60
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 41
    评论
### 回答1: yolov5数据增强copy-paste是一种数据增强方法,它可以通过将图像中的某些区域复制并粘贴到其他位置来生成新的训练数据。这种方法可以增加数据集的多样性,提高模型的鲁棒性和泛化能力。在yolov5中,copy-paste数据增强可以通过使用imgaug库来实现。 ### 回答2: YoloV5是一个非常流行的目标检测算法,而数据增强技术则是提高模型精度的重要手段。其中一种常见的数据增强方法是copy-paste,即将图片中的某个区域复制并粘贴到其他区域,从而生成更多的训练数据。 具体来说,copy-paste数据增强可以通过以下步骤实现: 1. 选择目标区域。通常情况下,我们会选择图片中包含目标物体的区域,以确保生成的新图片仍然包含该物体。 2. 复制目标区域。通过将目标区域从原图中复制出来,可以获得一个新的带有目标物体的小图像。 3. 选择粘贴位置。选择另一个区域作为粘贴位置,这里通常会选择一些背景区域或者其他未包含目标的区域。 4. 进行粘贴。将复制的区域粘贴到目标位置,就可以得到一个新的包含目标物体的图像。 5. 调整位置和大小。由于复制区域和粘贴位置的大小和形状可能不同,因此需要根据需要进行微调,以确保新图片的质量。 通过copy-paste数据增强,可以生成更多的训练数据,从而提高模型的泛化能力和鲁棒性。此外,还可以通过扭曲、旋转、颜色变换等技术进一步增强数据,以获得更好的训练效果。 ### 回答3: 在深度学习中,数据增强是提高模型性能的一种方式。YOLOv5是一种基于深度学习的目标检测算法,而Copy-Paste是YOLOv5数据增强的一种方式。以下是我对该数据增强方式的理解和解释。 Copy-Paste是指将一个物体从一张图像中复制到另一张图像中,然后将其放置在随机位置。该方法通过增加训练样本数量,增强了训练集的多样性,能提高模型的鲁棒性,从而提高模型的准确性和泛化能力。 Copy-Paste在YOLOv5中的具体实现步骤如下: 1. 随机从原始图像中选定一个物体作为复制对象。 2. 随机选择另一张与原始图像大小相同的图像,将选定的物体复制到该图像中。 3. 随机调整复制物体的大小和旋转角度,使其适应新的图像环境。 4. 随机选择新图像的位置,并将复制的物体粘贴到该位置上。 5. 计算图像中所有物体的坐标和类别,并将其转换为相对于图像大小的百分比。 使用Copy-Paste数据增强技术可以大大改善模型的性能,增加数据多样性以达到模型推广到更多的应用的目的,可以有效解决数据少的情况下模型过拟合问题。当然这个数据增强方法也有一定的缺陷,因为复制的物体可能不匹配目标图像的背景,会导致背景不连续甚至不真实。需要进行质量评估。然而,该方法可以通过调整参数来改进,比如增加复制物体的数量和增加旋转和平移的方式来进一步提高模型的性能。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

叶舟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值