转载https://blog.csdn.net/zhw864680355/article/details/89317741

# -*- coding:utf-8 -*-"""数据增强1. 翻转变换 flip2. 随机修剪 random crop3. 色彩抖动 color jittering4. 平移变换 shift5. 尺度变换 scale6. 对比度变换 contrast7. 噪声扰动 noise8. 旋转变换/反射变换 Rotation/reflection
"""# -*- coding:utf-8 -*-"""数据增强1. 翻转变换 flip2. 随机修剪 random crop3. 色彩抖动 color jittering4. 平移变换 shift5. 尺度变换 scale6. 对比度变换 contrast7. 噪声扰动 noise8. 旋转变换/反射变换 Rotation/reflection
"""from PIL import Image, ImageEnhance, ImageOps, ImageFile
import numpy as np
import random
import threading, os, time
import logging
import math
import shutillogger = logging.getLogger(__name__)
ImageFile.LOAD_TRUNCATED_IMAGES = Trueclass DataAugmentation:"""包含数据增强的八种方式"""def __init__(self):pass@staticmethoddef openImage(image):return Image.open(image, mode="r")@staticmethoddef randomFlip(image, mode=Image.FLIP_LEFT_RIGHT):"""对图像进行上下左右四个方面的随机翻转:param image: PIL的图像image:param model: 水平或者垂直方向的随机翻转模式,默认右向翻转:return: 翻转之后的图像model- Image.FLIP_LEFT_RIGHT,表示将图像左右翻转- Image.FLIP_TOP_BOTTOM,表示将图像上下翻转- Image.ROTATE_90,表示将图像逆时针旋转90°- Image.ROTATE_180,表示将图像逆时针旋转180°- Image.ROTATE_270,表示将图像逆时针旋转270°- Image.TRANSPOSE,表示将图像进行转置(相当于顺时针旋转90°)- Image.TRANSVERSE,表示将图像进行转置,再水平翻转"""# random_model = np.random.randint(0, 2)# flip_model = [Image.FLIP_LEFT_RIGHT, Image.FLIP_TOP_BOTTOM]# return image.transpose(flip_model[random_model])return image.transpose(mode)@staticmethoddef randomShift(image):# def randomShift(image, xoffset, yoffset=None):"""对图像进行平移操作:param image: PIL的图像image:param xoffset: x方向向右平移:param yoffset: y方向向下平移:return: 翻转之后的图像"""random_xoffset = np.random.randint(0, math.ceil(image.size[0] * 0.2))random_yoffset = np.random.randint(0, math.ceil(image.size[1] * 0.2))# return image.offset(xoffset = random_xoffset, yoffset = random_yoffset)return image.offset(random_xoffset)@staticmethoddef randomRotation(image, mode=Image.BICUBIC):"""对图像进行随机任意角度(0~360度)旋转:param mode 邻近插值,双线性插值,双三次B样条插值(default)--PIL.Image.BICUBIC--PIL.Image.LANCZOS--PIL.Image.BILINEAR--PIL.Image.NEAREST:param image PIL的图像image:return: 旋转转之后的图像"""random_angle = np.random.randint(1, 360)return image.rotate(random_angle, mode)@staticmethoddef randomCrop(image):"""对图像随意剪切,裁剪图像大小宽和高的2/3:param image: PIL的图像image:return: 剪切之后的图像"""image_width = image.size[0]image_height = image.size[1]crop_image_width = math.ceil(image_width * 2 / 3)crop_image_height = math.ceil(image_height * 2 / 3)x = np.random.randint(0, image_width - crop_image_width)y = np.random.randint(0, image_height - crop_image_height)random_region = (x, y, x + crop_image_width, y + crop_image_height)return image.crop(random_region)@staticmethoddef randomColor(image):"""对图像进行颜色抖动:param image: PIL的图像image:return: 有颜色色差的图像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)  # 调整图像锐度@staticmethoddef randomGaussian(image, mean=0.2, sigma=0.3):"""对图像进行高斯噪声处理:param image::return:"""def gaussianNoisy(im, mean=0.2, sigma=0.3):"""对图像做高斯噪音处理:param im: 单通道图像:param mean: 偏移量:param sigma: 标准差:return:"""for _i in range(len(im)):im[_i] += random.gauss(mean, sigma)return im# 将图像转化成数组img = np.asarray(image)img.flags.writeable = True  # 将数组改为读写模式width, height = img.shape[:2]try: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])except:img = imgreturn Image.fromarray(np.uint8(img))@staticmethoddef saveImage(image, path):try:image.save(path)except:print('not save img: ', path)passfiles = []def get_files(dir_path):global filesif os.path.exists(dir_path):parents = os.listdir(dir_path)for parent in parents:child = os.path.join(dir_path, parent)if os.path.exists(child) and os.path.isfile(child):# child = child.split('/')[4:]# str_child = '/'.join(child)files.append(child)elif os.path.isdir(child):get_files(child)return fileselse:return Noneif __name__ == '__main__':times = 1  # 重复次数imgs_dir = '/home/huadian/图片/12'new_imgs_dir = '/home/huadian/图片/13/'# if os.path.exists(new_imgs_dir):#    shutil.rmtree(new_imgs_dir)funcMap = {"flip": DataAugmentation.randomFlip,"rotation": DataAugmentation.randomRotation,"crop": DataAugmentation.randomCrop,"color": DataAugmentation.randomColor,"gaussian": DataAugmentation.randomGaussian}funcLists = {"flip", "rotation", "crop", "color", "gaussian"}# funcLists = {"flip", "rotation", "crop", "gaussian"}# funcLists = {"rotation",  "crop", "gaussian"}global _indeximgs_list = get_files(imgs_dir)for index_img, img in enumerate(imgs_list):if index_img != 0 and index_img % 50 == 0:print('now is dealing %d image' % (index_img))tmp_img_dir_list = img.split('/')[:-1]tmp_img_dir_list[0:len(new_imgs_dir.split('/'))] = new_imgs_dir.split('/')new_img_dir = '/'.join(tmp_img_dir_list)if not os.path.exists(new_img_dir):os.makedirs(new_img_dir)try:shutil.copy(img, os.path.join(new_img_dir, img.split('/')[-1]))except:passimg_name = img.split('/')[-1].split('.')[0]postfix = img.split('.')[1]  # 后缀if postfix.lower() in ['jpg', 'jpeg', 'png', 'bmp']:image = DataAugmentation.openImage(img)_index = 1for func in funcLists:if func == 'flip':flip_model = [Image.FLIP_LEFT_RIGHT, Image.FLIP_TOP_BOTTOM]for model_index in range(len(flip_model)):new_image = DataAugmentation.randomFlip(image, flip_model[model_index])img_path = os.path.join(new_img_dir, img_name + '_' + str(_index) + '.' + postfix)DataAugmentation.saveImage(new_image, img_path)_index += 1elif func == 'gaussian':new_image = DataAugmentation.randomGaussian(image)img_path = os.path.join(new_img_dir, img_name + '_' + str(_index) + '.' + postfix)DataAugmentation.saveImage(new_image, img_path)_index += 1else:for _i in range(0, times, 1):new_image = funcMap[func](image)img_path = os.path.join(new_img_dir, img_name + '_' + str(_index) + '.' + postfix)DataAugmentation.saveImage(new_image, img_path)_index += 1

数据增强操作(旋转、翻转、裁剪、色彩变化、高斯噪声等)相关推荐

  1. 【AutoML】如何选择最合适的数据增强操作

    大家好,欢迎来到专栏<AutoML>.在这个专栏中,我们会讲述AutoML技术在深度学习中的应用.这一期讲述在数据增强中的应用,这也是AutoML技术最早期的应用之一. 作者&编辑 ...

  2. 图像数据增强(平移,旋转,亮度变换,翻转,添加高斯噪声,缩放,裁剪)

    1.平移: import cv2 import tensorflow as tf import numpy as np from PIL import Image from skimage impor ...

  3. 深度学习原理与框架-卷积网络细节-数据增强策略 1.翻转 2.随机裁剪 3.平移 4.旋转角度...

    数据增强表示的是,在原始图像的基础上,对数据进行一定的改变,增加了数据样本的数量,但是数据的标签值并不发生改变, 图片中可以看出对猫这张图片进行了灰度值的变化,但是猫的标签并没有发生改变 常见的数据增 ...

  4. 目标检测的Tricks | 【Trick8】数据增强——随机旋转、平移、缩放、错切、hsv增强

    如有错误,恳请指出. 在之前使用opencv就介绍使用过一些常用的数据增强的实现方法,见:<数据增强 | 旋转.平移.缩放.错切.HSV增强>,当时介绍了旋转.平移.缩放.错切.HSV增强 ...

  5. 【数据增强】---- 使用 Pytorch 裁剪图片并保存

    文章目录 概述 实现方式 项目结构及代码 输出结果 补充 对文件夹里的所有图片批量裁剪 概述 最近需要制作一个数据集,由于数据集的数量不够,而这些数据集中的单张照片很大,因此可以通过裁剪的方式进行数据 ...

  6. 对图片数据集进行数据增强操作

    运行平台:pycharm 在对数据集进行训练的过程中,为了使网络模型具有更好的鲁棒性,通常我们需要对数据集进行数据增强处理,常见的处理方法有添加噪声.旋转.改变亮度等,如图1,2所示. 图1.原图(c ...

  7. coco数据集进行裁剪、数据增强过程中的ground_truth bbox的设定以及变化

    目录 前言: 1. 写入json文件时的 ground truth bbox 2. 导入图片 和 获取对应的 ground truth bbox 3. 进行数据增强后, 决定了 最终的 ground ...

  8. 最全可白嫖之高光谱图像数据处理(格式转换,数据增强,通道剪切,大小裁剪,光谱显示,折线图表示)

    目录 (一)高光谱谱格式转换之rar转mat格式 ①RAW转tiff步骤: ②tiff转mat步骤: (二)两种方法把高光谱图像缩放到0-1的数据集 (三)高光谱数据预处理成规定大小和规格的数据集 ( ...

  9. 盘点深度学习中的各种数据增强技巧

    1 什么是数据增强? 数据增强也叫数据扩增,意思是在不实质性的增加数据的情况下,让有限的数据产生等价于更多数据的价值. 比如上图,第1列是原图,后面3列是对第1列作一些随机的裁剪.旋转操作得来. 每张 ...

  10. 【技术综述】深度学习中的数据增强方法都有哪些?

    很多实际的项目,我们都难以有充足的数据来完成任务,要保证完美的完成任务,有两件事情需要做好:(1)寻找更多的数据.(2)充分利用已有的数据进行数据增强,今天就来说说数据增强. 作者 | 言有三 编辑 ...

最新文章

  1. DeepChem | 基于DeepChem的GCN预测化合物溶解度
  2. SQL Server procedure
  3. Docker容器的启动过程(七)
  4. 3-uboot-spl代码流程
  5. linux下 tar解压 gz解压 bz2等各种解压文件使用方法
  6. php写入文本乱码,如何解决PHP用fwrite写入文件中文乱码的问题
  7. java 安全发布对象_Java安全的发布对象
  8. hive内部表与外部表入门
  9. Hive 存储格式入门
  10. 《给予者》:害羞,内向,不善言辞,如何构建人脉?
  11. 直播APP源码,视频直播技术篇 。
  12. 复合函数求导经典例题_复合函数求导公式大全_复合函数求导法则_复合函数求导经典例题_复合函数求导导学案...
  13. 关于Tampermonkey(油猴)的安装和使用的小白教程
  14. 162手写板合封芯片专用IC输出可达50V外围简单SOP8封装
  15. Android开发之对上下两个图层的操作
  16. jdk1.8 在綫英文+有道翻譯版
  17. 中国软件测试有多少人,测试全国有多少人重名,查重名(无需安装软件)
  18. hdu-1225-Football Score
  19. 笔试题-搜狐手机网Python开发工程师
  20. We found potential security vulnerabilities in your dependencies. Only the owner of this reposito...

热门文章

  1. 简单网络传递加密数据
  2. Hibernate入门案例
  3. ubuntu如何修改terminal终端的主机名
  4. 用nltk模仿莎士比亚写十四行诗
  5. nodejs后台系列--第五篇-购买云服务器,安装宝塔面板
  6. TypeError: Cannot read property ‘forceUpdate‘ of undefined
  7. npm install -g @vue/cli时 -4048 npm ERR! Error: EPERM: operation not permitted, lstat报错的几种解决方案
  8. Linux下安装mysql(yum、二进制包、源码包)
  9. c语言键盘函数空格,C语言中关于scanf函数的用法
  10. 数据抽取oracle_【跟我学】特征抽取算法与应用