PyTorch实现图片的数据增广方法是什么
Admin 2022-09-21 群英技术资讯 442 次浏览
数据增强就是增强一个已有数据集,使得有更多的多样性。对于图片数据来说,就是改变图片的颜色和形状等等。比如常见的:
左右翻转,对于大多数数据集都可以使用;
上下翻转:部分数据集不适合使用;
图片切割:从图片中切割出一个固定的形状,
改变图片的颜色
加载相关包。
import torch import torchvision import matplotlib from torch import nn from torchvision import transforms from PIL import Image from IPython import display from matplotlib import pyplot as plt
选取一个狗的图片作为示例:
def set_figsize(figsize=(3.5, 2.5)): display.set_matplotlib_formats('svg') plt.rcParams['figure.figsize'] = figsize def show_images(imgs, num_rows, num_cols, titles=None, scale=1.5): r""" 展示一列图片 img: Image对象的列表 """ figsize = (num_cols * scale, num_rows * scale) fig, axes = plt.subplots(num_rows, num_cols, figsize=figsize) axes = axes.flatten() for i, (ax, img) in enumerate(zip(axes, imgs)): if torch.is_tensor(img): ax.imshow(img.numpy()) else: ax.imshow(img) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.get_xaxis().set_label('x') if titles: ax.set_title(titles[i]) return axes set_figsize() img = Image.open('img/dog1.jpg') plt.imshow(img);
def apply(img, aug, num_rows=2, num_clos=4, scale=1.5): # 对图片应用图片增广 # img: Image object # aug: 增广操作 Y = [aug(img) for _ in range(num_clos * num_rows)] d2l.show_images(Y, num_rows, num_clos, scale=scale)
class RandomHorizontalFlip(torch.nn.modules.module.Module): r''' RandomHorizontalFlip(p=0.5) 给图片一个一定概率的水平翻转操作,如果是Tensor,要求形状为[..., H, W] Args: p: float, 图片翻转的概率,默认值0.5 ''' def __init__(self, p=0.5): pass
示例。可以看到,有一般的几率对图片进行了水平翻转。
aug = transforms.RandomHorizontalFlip(0.5) apply(img, aug)
class RandomVerticalFlip(torch.nn.modules.module.Module): r''' RandomVerticalFlip(p=0.5) 给图片一个一定概率的上下翻转操作,如果是Tensor,要求形状为[..., H, W] Args: p: float, 图片翻转的概率,默认值0.5 ''' def __init__(self, p=0.5): pass
示例。可以看到,有一般的几率对图片进行了上下翻转。
aug = transforms.RandomHorizontalFlip(0.5) apply(img, aug)
class RandomRotation(torch.nn.modules.module.Module): r''' 将图片旋转一定角度。 ''' def __init__(self, degrees, interpolation=<InterpolationMode.NEAREST: 'nearest'>, expand=False, center=None, fill=0): r""" Args: degrees: number or sequence, 可选择的角度范围(min, max), 如果是一个数字,则范围是(-degrees, +degrees) interpolation: Default is ``InterpolationMode.NEAREST``. expand: bool, 如果为True,则扩展输出,使其足够大来容纳整个旋转的图像 如果为False, 将输出图像与输入图像的大小相同。 center: sequence, 以左上角为原点的旋转中心,默认是图片中心。 fill: sequence or number: 旋转图像外部区域的像素填充值,默认0。 """ pass def forward(self, input): r""" Args: img: PIL Image or Tensor, 被旋转的图片。 Return: PIL Image or Tensor: 旋转后的图片。 """ pass
使用实例:
aug = transforms.RandomRotation(degrees=(-90, 90), fill=128) apply(img, aug)
class CenterCrop(torch.nn.modules.module.Module): r''' 中心裁切。 ''' def __init__(self, size): r""" Args: size: sequence or int, 裁切尺寸(H, W), 如果是int,尺寸为(size, size) """ pass def forward(self, input): r""" Args: img: PIL Image or Tensor, 被裁切的图片。 Return: PIL Image or Tensor: 裁切后的图片。 """ pass
实例:
aug = transforms.CenterCrop((200, 300)) apply(img, aug)
class RandomCrop(torch.nn.modules.module.Module): r''' 随机裁切。 ''' def __init__(self, size): r""" Args: size: sequence or int, 裁切尺寸(H, W), 如果是int,尺寸为(size, size) padding: sequence or int, 填充大小, 如果值为 a , 四周填充a个像素 如果值为 (a, b), 左右填充a,上下填充b 如果值为 (a, b, c, d), 左上右下依次填充 pad_if_need: bool, 如果裁切尺寸大于原图片,则填充 fill: number or str or tuple: 填充像素的值 padding_mode: str, 填充类型。 `constant`: 使用 fill 填充 `edge`: 使用边缘的最后一个值填充在图像边缘。 `reflect`: 镜像填充 """ pass def forward(self, input): r""" Args: img: PIL Image or Tensor, 被裁切的图片。 Return: PIL Image or Tensor: 裁切后的图片。 """ pass
示例:
aug = transforms.RandomCrop((200, 300)) apply(img, aug)
输出:
class RandomResizedCrop(torch.nn.modules.module.Module): r''' 随机裁切, 并重设尺寸。 ''' def __init__(self, size, scale=(0.08, 1.0), ratio=(0.75, 1.3333333333333333)): r""" Args: size: sequence or int, 需要输出的尺寸(H, W), 如果是int,尺寸为(size, size) scale: tuple of float, 原始图片中裁切大小,百分比 ratio: tuple of float, resize前的裁切的纵横比范围 """ pass def forward(self, input): r""" Args: img: PIL Image or Tensor, 被裁切的图片。 Return: PIL Image or Tensor: 输出的图片。 """ pass
示例:
aug = transforms.RandomResizedCrop((200, 200), scale=(0.2, 1)) apply(img, aug)
class ColorJitter(torch.nn.modules.module.Module): r''' 修改颜色。 ''' def __init__(self, brightness=0, contrast=0, saturation=0, hue=0): r""" Args: brightness: float or tuple of float (min, max), 亮度的偏移幅度,范围[max(0, 1 - brightness), 1 + brightness] contrast: float or tuple of float (min, max), 对比度偏移幅度,范围[max(0, 1 - contrast), 1 + contrast] saturation: float or tuple of float (min, max), 饱和度偏移幅度,范围[max(0, 1 - saturation), 1 + saturation] hue: float or tuple of float (min, max), 色相偏移幅度,范围[-hue, hue] """ pass def forward(self, input): r""" Args: img: PIL Image or Tensor, 输入的图片。 Return: PIL Image or Tensor: 输出的图片。 """ pass
示例:
aug = transforms.ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.5) apply(img, aug)
train_augs = transforms.Compose([transforms.RandomHorizontalFlip(), torchvision.transforms.ToTensor()]) dataset = torchvision.datasets.CIFAR10(root="../data", train=is_train, transform=augs, download=True)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
这篇文章主要介绍了Python数据挖掘Pandas,pandas是基于numpy模块构建的,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
这篇文章主要分享的是Python日志模块logging的使用方法总结,ogging模块默认级别是WARNING,意味着只会追踪该级别以上的事件,除非更改日志配置,想了解更多相关资料的小伙伴可以参考下面文章内容
分词工具在Python中,会经常使用到,而比较常的分词工具有jieba 分词、pkuseg 分词、FoolNLTK 分词和THULAC,这四种,那么究竟哪个更好用呢?
这篇文章主要介绍了PyTorch一小时掌握之图像识别实战篇,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
随机整数:>>>importrandom>>>random randint(0,99)21随机选取0到100间的偶数:>>>importrandom>>>random randrange(0,101,2)42随机浮点数
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008