PyTorch实现图片的数据增广方法是什么
Admin 2022-09-21 群英技术资讯 1110 次浏览
在日常操作或是项目的实际应用中,有不少朋友对于“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进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
这篇文章给大家分享的是NumPy中多维数组的相关内容,下文会介绍多维数组的创建、属性、元素的类型转换和运算等等。对大家学习和理解ndarray多维数组有一定的帮助,感兴趣的朋友接下来一起跟随小编看看吧。
这篇文章主要介绍了python 如何破解加密zip文件的密码,帮助大家更好的理解和学习使用python,感兴趣的朋友可以了解下
这篇文章主要介绍了Python matplotlib绘制散点图配置(万能模板案例),散点图是指在 回归分析中,数据点在直角坐标系平面上的分布图,散点图表示因变量随自变量而变化的大致趋势,据此可以选择合适的函数对数据点进行拟合
这篇文章主要为大家详细介绍了如何利用Python语言编写一个爆炸信息窗口脚本,文中的示例代码讲解详细,感兴趣的小伙伴可以尝试一下
这篇文章主要为大家介绍了PyTorch实现联邦学习的基本算法FedAvg,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
成为群英会员,开启智能安全云计算之旅
立即注册关注或联系群英网络
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核准(ICP备案)粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008