语义分割数据增强(Data augmentation for semantic segmentation)

数据增强

深度学习模型的鲁棒性(robustness)和泛化性受到训练数据的多样性和数据量所影响。数据增强(data augmentation)是机器学习和深度学习中经常采用的一个方法,其目的是扩大训练样本的数量。

语义分割是计算机视觉一个重要的下游任务,语义分割的数据增强通常需要对图像及其对应的标签做相同的增强处理


本文总结了3种常用的增强方式:(1)旋转,(2)翻转,(3)裁剪。所有操作均采用opencv库进行


首先使用opencv定义数据读取和保存函数

# 定义数据读取函数
import cv2
import os
import numpy as np
 ___________________________________________________________
 
 def read_data(file, mode=1):
    """
    Args:
        file: 数据路径
        mode: bool值,若读取3通道则1,读取灰度图则为0

    Returns:

    """
    if mode == 1:
        img = cv2.imread(file)
        # print(img.shape)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        return img
    if mode == 0:
        img = cv2.imread(file, cv2.IMREAD_GRAYSCALE)
        return img
    else:
        raise ValueError("mode should be a bool number 1 or 0")


def save_data(save_pth, img):
    img = img.astype(np.uint8)
    cv2.imwrite(save_pth, img)


旋转操作(Rotate)

	def rotate(img, gt, angle=10):
		"""
		angle: 旋转的角度
		"""	
	    img = read_data(img, 1)
	    gt = read_data(gt, 0)
	    assert img.shape[:2] == gt.shape[:2]
	
	    h, w = img.shape[:2]
	    center = (w / 2, h / 2)
	    mat = cv2.getRotationMatrix2D(center, angle, scale=1)
	    rotated_img = cv2.warpAffine(img, mat, (h, w))
	    rotated_gt = cv2.warpAffine(gt, mat, (h, w))
	    return rotated_img, rotated_gt

翻转操作(flip)

# 翻转图片(水平和垂直) 核心函数:cv.flip()
def flip(img, gt, direction=1):
    """
    Args:
        img:
        direction: bool, 1表示水平翻转,0表示垂直翻转
    Returns:

    """
    # 如果传入的是图像路径:则先调用函数读取图像,再对图像进行翻转
    if type(img) == str:
        img = read_data(img, 1)
        gt = read_data(gt, 0)
        assert img.shape[:2] == gt.shape[:2]
    # 如果传入的是读取的图像数据,则直接对图像进行翻转
    assert img.shape[:2] == gt.shape[:2]
    flipped_img = cv2.flip(img, direction)
    flipped_gt = cv2.flip(gt, direction)
    return flipped_img, flipped_gt

裁剪操作(crop)

# 在输入图像种的左上角,右上角,左下角,右上角,中间分别裁剪大小为(512*512)大小的子图像
def crop(img, gt):
    img = read_data(img, 1)
    gt = read_data(gt, 0)
    assert img.shape[:2] == gt.shape[:2]
		
	# 左上角
    upL_subim, upL_subgt = img[:512, :512, :], gt[:512, :512]
    # 右上角
    upR_subim, upR_subgt = img[:512, -512:, :], gt[:512, -512:]
    # 左下角
    bottomL_subim, bottomL_subgt = img[-512:, :512, :], gt[-512:, :512]
    # 右下角
    bottomR_subim, bottomR_subgt = img[-512:, -512:, :], gt[-512:, -512:]
	# 中间
   	(h, w) = img.shape[:2]
    h_ctr, w_ctr = int(h/2), int(w/2)
    center_subim, center_subgt = img[(h_ctr - 256):(h_ctr + 256), (w_ctr - 256):(w_ctr + 256), :],\
                                 gt[(h_ctr - 256):(h_ctr + 256), (w_ctr - 256):(w_ctr + 256)],
                                                                                   (w - 256):(w + 256)]

    return (upL_subim, upL_subgt), (upR_subim, upR_subgt), (bottomL_subim, bottomL_subgt), (
    bottomR_subim, bottomR_subgt), (center_subim, center_subgt)
  • 5
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个示例的Python代码,用于对指定类别的labelme标注的语义分割数据进行增强: ```python import os import cv2 import numpy as np def semantic_segmentation_augmentation(directory, save_directory, target_class): # 遍历指定目录下的文件 for filename in os.listdir(directory): if filename.endswith(".json"): # 查找以.json结尾的文件 json_file = os.path.join(directory, filename) image_file = json_file.replace(".json", ".jpg") # 将.json替换为.jpg if os.path.isfile(image_file): # 检查对应的图片文件是否存在 # 读取图片文件 image = cv2.imread(image_file) height, width, _ = image.shape # 读取JSON文件并获取标注信息 with open(json_file, 'r') as f: json_data = json.load(f) # 创建空白的语义分割图像 seg_image = np.zeros((height, width), dtype=np.uint8) # 处理每个标注对象 for shape in json_data['shapes']: class_name = shape['label'] if class_name == target_class: points = shape['points'] polygon_points = np.array(points, dtype=np.int32) cv2.fillPoly(seg_image, [polygon_points], 255) # 将增强后的语义分割图像保存到指定目录 save_path = os.path.join(save_directory, filename.replace(".json", ".png")) cv2.imwrite(save_path, seg_image) print(f"语义分割图像保存成功:{save_path}") else: print(f"找不到对应的图片文件:{image_file}") # 指定包含labelme标注文件的目录和保存增强后数据的目录 directory = "path/to/labelme/files" save_directory = "path/to/save/augmented/data" # 指定目标类别名称 target_class = "class_name" semantic_segmentation_augmentation(directory, save_directory, target_class) ``` 你需要将代码中的`"path/to/labelme/files"`替换为包含标注文件的实际目录路径,将`"path/to/save/augmented/data"`替换为你想要保存增强后数据的目录路径,将`"class_name"`替换为你想要增强的目标类别名称。运行代码后,它会遍历目录中的所有.json文件,读取标注信息并创建相应的语义分割图像,然后将增强后的语义分割图像保存到指定目录。 希望这可以帮到你!如果有任何问题,请随时问我。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值