PyTorch实现图片的数据增广方法是什么
Admin 2022-09-21 群英技术资讯 823 次浏览
在日常操作或是项目的实际应用中,有不少朋友对于“PyTorch实现图片的数据增广方法是什么”的问题会存在疑惑,下面小编给大家整理和分享了相关知识和资料,易于大家学习和理解,有需要的朋友可以借鉴参考,下面我们一起来了解一下吧。数据增强就是增强一个已有数据集,使得有更多的多样性。对于图片数据来说,就是改变图片的颜色和形状等等。比如常见的:
左右翻转,对于大多数数据集都可以使用;
上下翻转:部分数据集不适合使用;
图片切割:从图片中切割出一个固定的形状,
改变图片的颜色
加载相关包。
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和PyQT5实现简易的文档格式转换器,支持.txt/.xlsx/.csv格式的转换。感兴趣的小伙伴可以跟随小编一起学习一下
内容介绍time模块datetime模块总结time模块time模块,也就是时间模块,用来进行一些与时间有关的操作。其使用方法为:importtimeprint(time.time())
这篇文章主要介绍了Python实战之实现康威生命游戏,文中有非常详细的代码示例,对正在学习python的小伙伴们有非常好的帮助,需要的朋友可以参考下
Python内置函数-float()函数。float() 函数用于将整数和字符串转换成浮点数。
在深度学习中训练模型的过程中读取图片数据,如果将图片数据全部读入内存是不现实的,所以有必要使用生成器来读取数据。通过列表生成式,我们可以直接创建一个列表。但是,受到内存限制,列表容量肯定是有限的。而且,创建一个包含100万个元素的列表,不仅占用很大的存储空间,如果我们仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了。
成为群英会员,开启智能安全云计算之旅
立即注册关注或联系群英网络
7x24小时售前:400-678-4567
7x24小时售后:0668-2555666
24小时QQ客服
群英微信公众号
CNNIC域名投诉举报处理平台
服务电话:010-58813000
服务邮箱:service@cnnic.cn
投诉与建议:0668-2555555
Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008