#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 18-7-30 下午3:21
# @File : DataAgument.py
# @Software: PyCharm
# @Author : wxw
# @Contact : xwwei@lighten.ai
# @Desc : 数据增强
import numpy as np
from PIL import Image, ImageEnhance
import cv2
def randomColor(image):
"""
颜色抖动
"""
random_factor = np.random.randint(0, 31) / 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, 31) / 10. # 随机因子
return ImageEnhance.Sharpness(contrast_image).enhance(random_factor) # 调整图像锐度
def PCAJitter(img):
"""
PCA抖动
"""
image = img
img = image / 255.0
img_size = img.size // 3
img1 = img.reshape(img_size, 3)
img1 = np.transpose(img1)
img_cov = np.cov([img1[0], img1[1], img1[2]])
lamda, p = np.linalg.eig(img_cov)
p = np.transpose(p)
alpha0 = np.random.uniform(0, 0.3)
alpha1 = np.random.uniform(0, 0.3)
alpha2 = np.random.uniform(0, 0.3)
v = np.transpose((alpha0*img1[0], alpha1*img1[1], alpha2*img1[2]))
add_num = np.dot(v, p).reshape(np.shape(img))
return np.array(image + add_num)
for _ in range(30):
image = cv2.imread('ss.jpg')
img = PCAJitter(image)
img = img.astype(np.uint8)
# cv2 转 PIL
img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
img = randomColor(img)
# PIL 转 cv2
img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
cv2.imshow('cc', img)
cv2.waitKey(0)
网友评论