乐趣区

关于python:通过颜色扰动完成数据增广

# -*- coding:utf-8 -*-


from PIL import Image, ImageEnhance
import numpy as np
import random
import cv2



def randomColor(image):
    """
    对图像进行色彩抖动
    :param image: PIL 的图像 image
    :return: 有色彩色差的图像 image
    """
    image = Image.fromarray(np.uint8(image))

    random_factor = np.random.randint(0, 21) / 10.  # 随机因子
    color_image = ImageEnhance.Color(image).enhance(random_factor)  # 调整图像的饱和度

    random_factor = np.random.randint(10, 21) / 10.  # 随机因子
    brightness_image = ImageEnhance.Brightness(color_image).enhance(random_factor)  # 调整图像的亮度

    random_factor = np.random.randint(10, 21) / 10.  # 随机因 1 子
    contrast_image = ImageEnhance.Contrast(brightness_image).enhance(random_factor)  # 调整图像对比度

    random_factor = np.random.randint(0, 21) / 10.  # 随机因子
    sharp_image = ImageEnhance.Sharpness(contrast_image).enhance(random_factor)  # 调整图像锐度

    final = np.asarray(sharp_image) 
    return final



def randomGaussian(img, mean=0.2, sigma=0.5):
    """
    对图像进行高斯噪声解决
    :param image:
    :return:
    """def gaussianNoisy(im, mean=0.2, sigma=0.5):"""
        对图像做高斯乐音解决
        :param im: 单通道图像
        :param mean: 偏移量
        :param sigma: 标准差
        :return:
        """
        for _i in range(len(im)):
            im[_i] += random.gauss(mean, sigma)
        return im

    
    img.flags.writeable = True  # 将数组改为读写模式
    width, height = img.shape[:2]
    img_r = gaussianNoisy(img[:, :, 0].flatten(), mean, sigma)
    img_g = gaussianNoisy(img[:, :, 1].flatten(), mean, sigma)
    img_b = gaussianNoisy(img[:, :, 2].flatten(), mean, sigma)
    img[:, :, 0] = img_r.reshape([width, height])
    img[:, :, 1] = img_g.reshape([width, height])
    img[:, :, 2] = img_b.reshape([width, height])
    return img



# 均值滤波
def ranndom_blur(img, ksize=(3, 3)):
    img_blur = cv2.blur(src=img, ksize=ksize)
    return img_blur




if __name__ == '__main__':
    
   
    pic = cv2.imread('./test.jpg')
  

    a = randomColor(pic)
    cv2.imwrite('randomColor.jpg', a)
   
    b = randomGaussian(pic)
    cv2.imwrite('randomGaussian.jpg', b)

    c = ranndom_blur(pic)
    cv2.imwrite('ranndom_blur.jpg', c)

退出移动版