|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | + |
| 4 | +@description: |
| 5 | +""" |
| 6 | + |
| 7 | +"""数据增强 |
| 8 | + 1. 翻转变换 flip |
| 9 | + 2. 随机修剪 random crop |
| 10 | + 3. 色彩抖动 color jittering |
| 11 | + 4. 平移变换 shift |
| 12 | + 5. 尺度变换 scale |
| 13 | + 6. 对比度变换 contrast |
| 14 | + 7. 噪声扰动 noise |
| 15 | + 8. 旋转变换/反射变换 Rotation/reflection |
| 16 | + author: XiJun.Gong |
| 17 | + date:2016-11-29 |
| 18 | +""" |
| 19 | + |
| 20 | +from PIL import Image, ImageEnhance, ImageOps, ImageFile |
| 21 | +import numpy as np |
| 22 | +import random |
| 23 | +import threading, os, time |
| 24 | +import logging |
| 25 | + |
| 26 | +logger = logging.getLogger(__name__) |
| 27 | +ImageFile.LOAD_TRUNCATED_IMAGES = True |
| 28 | + |
| 29 | + |
| 30 | +class DataAugmentation: |
| 31 | + """ |
| 32 | + 包含数据增强的八种方式 |
| 33 | + """ |
| 34 | + |
| 35 | + def __init__(self): |
| 36 | + pass |
| 37 | + |
| 38 | + @staticmethod |
| 39 | + def openImage(image): |
| 40 | + return Image.open(image, mode="r") |
| 41 | + |
| 42 | + @staticmethod |
| 43 | + def randomRotation(image, mode=Image.BICUBIC): |
| 44 | + """ |
| 45 | + 对图像进行随机任意角度(0~360度)旋转 |
| 46 | + :param mode 邻近插值,双线性插值,双三次B样条插值(default) |
| 47 | + :param image PIL的图像image |
| 48 | + :return: 旋转转之后的图像 |
| 49 | + """ |
| 50 | + random_angle = np.random.randint(1, 360) |
| 51 | + return image.rotate(random_angle, mode) |
| 52 | + |
| 53 | + @staticmethod |
| 54 | + def randomCrop(image): |
| 55 | + """ |
| 56 | + 对图像随意剪切,考虑到图像大小范围(68,68),使用一个一个大于(36*36)的窗口进行截图 |
| 57 | + :param image: PIL的图像image |
| 58 | + :return: 剪切之后的图像 |
| 59 | + """ |
| 60 | + image_width = image.size[0] |
| 61 | + image_height = image.size[1] |
| 62 | + crop_win_size = np.random.randint(40, 68) |
| 63 | + random_region = ( |
| 64 | + (image_width - crop_win_size) >> 1, (image_height - crop_win_size) >> 1, (image_width + crop_win_size) >> 1, |
| 65 | + (image_height + crop_win_size) >> 1) |
| 66 | + return image.crop(random_region) |
| 67 | + |
| 68 | + @staticmethod |
| 69 | + def randomColor(image): |
| 70 | + """ |
| 71 | + 对图像进行颜色抖动 |
| 72 | + :param image: PIL的图像image |
| 73 | + :return: 有颜色色差的图像image |
| 74 | + """ |
| 75 | + random_factor = np.random.randint(0, 31) / 10. # 随机因子 |
| 76 | + color_image = ImageEnhance.Color(image).enhance(random_factor) # 调整图像的饱和度 |
| 77 | + random_factor = np.random.randint(10, 21) / 10. # 随机因子 |
| 78 | + brightness_image = ImageEnhance.Brightness(color_image).enhance(random_factor) # 调整图像的亮度 |
| 79 | + random_factor = np.random.randint(10, 21) / 10. # 随机因1子 |
| 80 | + contrast_image = ImageEnhance.Contrast(brightness_image).enhance(random_factor) # 调整图像对比度 |
| 81 | + random_factor = np.random.randint(0, 31) / 10. # 随机因子 |
| 82 | + return ImageEnhance.Sharpness(contrast_image).enhance(random_factor) # 调整图像锐度 |
| 83 | + |
| 84 | + @staticmethod |
| 85 | + def randomGaussian(image, mean=0.2, sigma=0.3): |
| 86 | + """ |
| 87 | + 对图像进行高斯噪声处理 |
| 88 | + :param image: |
| 89 | + :return: |
| 90 | + """ |
| 91 | + |
| 92 | + def gaussianNoisy(im, mean=0.2, sigma=0.3): |
| 93 | + """ |
| 94 | + 对图像做高斯噪音处理 |
| 95 | + :param im: 单通道图像 |
| 96 | + :param mean: 偏移量 |
| 97 | + :param sigma: 标准差 |
| 98 | + :return: |
| 99 | + """ |
| 100 | + for _i in range(len(im)): |
| 101 | + im[_i] += random.gauss(mean, sigma) |
| 102 | + return im |
| 103 | + |
| 104 | + # 将图像转化成数组 |
| 105 | + img = np.asarray(image) |
| 106 | + img.flags.writeable = True # 将数组改为读写模式 |
| 107 | + width, height = img.shape[:2] |
| 108 | + img_r = gaussianNoisy(img[:, :, 0].flatten(), mean, sigma) |
| 109 | + img_g = gaussianNoisy(img[:, :, 1].flatten(), mean, sigma) |
| 110 | + img_b = gaussianNoisy(img[:, :, 2].flatten(), mean, sigma) |
| 111 | + img[:, :, 0] = img_r.reshape([width, height]) |
| 112 | + img[:, :, 1] = img_g.reshape([width, height]) |
| 113 | + img[:, :, 2] = img_b.reshape([width, height]) |
| 114 | + return Image.fromarray(np.uint8(img)) |
| 115 | + |
| 116 | + @staticmethod |
| 117 | + def saveImage(image, path): |
| 118 | + image.save(path) |
| 119 | + |
| 120 | + |
| 121 | +def makeDir(path): |
| 122 | + try: |
| 123 | + if not os.path.exists(path): |
| 124 | + if not os.path.isfile(path): |
| 125 | + # os.mkdir(path) |
| 126 | + os.makedirs(path) |
| 127 | + return 0 |
| 128 | + else: |
| 129 | + return 1 |
| 130 | + except Exception as e: |
| 131 | + print(e) |
| 132 | + return -2 |
| 133 | + |
| 134 | + |
| 135 | +def imageOps(func_name, image, des_path, file_name, times=5): |
| 136 | + funcMap = {"randomRotation": DataAugmentation.randomRotation, |
| 137 | + "randomCrop": DataAugmentation.randomCrop, |
| 138 | + "randomColor": DataAugmentation.randomColor, |
| 139 | + "randomGaussian": DataAugmentation.randomGaussian |
| 140 | + } |
| 141 | + if funcMap.get(func_name) is None: |
| 142 | + logger.error("%s is not exist", func_name) |
| 143 | + return -1 |
| 144 | + |
| 145 | + for _i in range(0, times, 1): |
| 146 | + new_image = funcMap[func_name](image) |
| 147 | + DataAugmentation.saveImage(new_image, os.path.join(des_path, func_name + str(_i) + file_name)) |
| 148 | + |
| 149 | + |
| 150 | +opsList = {"randomRotation", "randomCrop", "randomColor", "randomGaussian"} |
| 151 | + |
| 152 | + |
| 153 | +def threadOPS(path, new_path): |
| 154 | + """ |
| 155 | + 多线程处理事务 |
| 156 | + :param src_path: 资源文件 |
| 157 | + :param des_path: 目的地文件 |
| 158 | + :return: |
| 159 | + """ |
| 160 | + if os.path.isdir(path): |
| 161 | + img_names = os.listdir(path) |
| 162 | + else: |
| 163 | + img_names = [path] |
| 164 | + for img_name in img_names: |
| 165 | + print(img_name) |
| 166 | + tmp_img_name = os.path.join(path, img_name) |
| 167 | + if os.path.isdir(tmp_img_name): |
| 168 | + if makeDir(os.path.join(new_path, img_name)) != -1: |
| 169 | + threadOPS(tmp_img_name, os.path.join(new_path, img_name)) |
| 170 | + else: |
| 171 | + print('create new dir failure') |
| 172 | + return -1 |
| 173 | + # os.removedirs(tmp_img_name) |
| 174 | + elif tmp_img_name.split('.')[1] != "DS_Store": |
| 175 | + # 读取文件并进行操作 |
| 176 | + image = DataAugmentation.openImage(tmp_img_name) |
| 177 | + threadImage = [0] * 5 |
| 178 | + _index = 0 |
| 179 | + for ops_name in opsList: |
| 180 | + threadImage[_index] = threading.Thread(target=imageOps, |
| 181 | + args=(ops_name, image, new_path, img_name,)) |
| 182 | + threadImage[_index].start() |
| 183 | + _index += 1 |
| 184 | + time.sleep(0.2) |
| 185 | + |
| 186 | + |
| 187 | +if __name__ == '__main__': |
| 188 | + threadOPS("data","new_data") |
0 commit comments