PyTorch之图像和Tensor填充的实例


Posted in Python onAugust 18, 2019

在PyTorch中可以对图像和Tensor进行填充,如常量值填充,镜像填充和复制填充等。在图像预处理阶段设置图像边界填充的方式如下:

import vision.torchvision.transforms as transforms
 
img_to_pad = transforms.Compose([
    transforms.Pad(padding=2, padding_mode='symmetric'),
    transforms.ToTensor(),
   ])

对Tensor进行填充的方式如下:

import torch.nn.functional as F
 
feature = feature.unsqueeze(0).unsqueeze(0)
avg_feature = F.pad(feature, pad = [1, 1, 1, 1], mode='replicate')

这里需要注意一点的是,transforms.Pad只能对PIL图像格式进行填充,而F.pad可以对Tensor进行填充,目前F.pad不支持对2D Tensor进行填充,可以通过unsqueeze扩展为4D Tensor进行填充。

F.pad的部分源码如下:

@torch._jit_internal.weak_script
def pad(input, pad, mode='constant', value=0):
 # type: (Tensor, List[int], str, float) -> Tensor
 r"""Pads tensor.
 Pading size:
  The number of dimensions to pad is :math:`\left\lfloor\frac{\text{len(pad)}}{2}\right\rfloor`
  and the dimensions that get padded begins with the last dimension and moves forward.
  For example, to pad the last dimension of the input tensor, then `pad` has form
  `(padLeft, padRight)`; to pad the last 2 dimensions of the input tensor, then use
  `(padLeft, padRight, padTop, padBottom)`; to pad the last 3 dimensions, use
  `(padLeft, padRight, padTop, padBottom, padFront, padBack)`.
 Padding mode:
  See :class:`torch.nn.ConstantPad2d`, :class:`torch.nn.ReflectionPad2d`, and
  :class:`torch.nn.ReplicationPad2d` for concrete examples on how each of the
  padding modes works. Constant padding is implemented for arbitrary dimensions.
  Replicate padding is implemented for padding the last 3 dimensions of 5D input
  tensor, or the last 2 dimensions of 4D input tensor, or the last dimension of
  3D input tensor. Reflect padding is only implemented for padding the last 2
  dimensions of 4D input tensor, or the last dimension of 3D input tensor.
 .. include:: cuda_deterministic_backward.rst
 Args:
  input (Tensor): `Nd` tensor
  pad (tuple): m-elem tuple, where :math:`\frac{m}{2} \leq` input dimensions and :math:`m` is even.
  mode: 'constant', 'reflect' or 'replicate'. Default: 'constant'
  value: fill value for 'constant' padding. Default: 0
 Examples::
  >>> t4d = torch.empty(3, 3, 4, 2)
  >>> p1d = (1, 1) # pad last dim by 1 on each side
  >>> out = F.pad(t4d, p1d, "constant", 0) # effectively zero padding
  >>> print(out.data.size())
  torch.Size([3, 3, 4, 4])
  >>> p2d = (1, 1, 2, 2) # pad last dim by (1, 1) and 2nd to last by (2, 2)
  >>> out = F.pad(t4d, p2d, "constant", 0)
  >>> print(out.data.size())
  torch.Size([3, 3, 8, 4])
  >>> t4d = torch.empty(3, 3, 4, 2)
  >>> p3d = (0, 1, 2, 1, 3, 3) # pad by (0, 1), (2, 1), and (3, 3)
  >>> out = F.pad(t4d, p3d, "constant", 0)
  >>> print(out.data.size())
  torch.Size([3, 9, 7, 3])
 """
 assert len(pad) % 2 == 0, 'Padding length must be divisible by 2'
 assert len(pad) // 2 <= input.dim(), 'Padding length too large'
 if mode == 'constant':
  ret = _VF.constant_pad_nd(input, pad, value)
 else:
  assert value == 0, 'Padding mode "{}"" doesn\'t take in value argument'.format(mode)
  if input.dim() == 3:
   assert len(pad) == 2, '3D tensors expect 2 values for padding'
   if mode == 'reflect':
    ret = torch._C._nn.reflection_pad1d(input, pad)
   elif mode == 'replicate':
    ret = torch._C._nn.replication_pad1d(input, pad)
   else:
    ret = input # TODO: remove this when jit raise supports control flow
    raise NotImplementedError
 
  elif input.dim() == 4:
   assert len(pad) == 4, '4D tensors expect 4 values for padding'
   if mode == 'reflect':
    ret = torch._C._nn.reflection_pad2d(input, pad)
   elif mode == 'replicate':
    ret = torch._C._nn.replication_pad2d(input, pad)
   else:
    ret = input # TODO: remove this when jit raise supports control flow
    raise NotImplementedError
 
  elif input.dim() == 5:
   assert len(pad) == 6, '5D tensors expect 6 values for padding'
   if mode == 'reflect':
    ret = input # TODO: remove this when jit raise supports control flow
    raise NotImplementedError
   elif mode == 'replicate':
    ret = torch._C._nn.replication_pad3d(input, pad)
   else:
    ret = input # TODO: remove this when jit raise supports control flow
    raise NotImplementedError
  else:
   ret = input # TODO: remove this when jit raise supports control flow
   raise NotImplementedError("Only 3D, 4D, 5D padding with non-constant padding are supported for now")
 return ret

以上这篇PyTorch之图像和Tensor填充的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
详解Python中DOM方法的动态性
Apr 11 Python
python数据结构链表之单向链表(实例讲解)
Jul 25 Python
Flask框架各种常见装饰器示例
Jul 17 Python
python 剪切移动文件的实现代码
Aug 02 Python
如何在Django配置文件里配置session链接
Aug 06 Python
Python pandas实现excel工作表合并功能详解
Aug 29 Python
pyhton中__pycache__文件夹的产生与作用详解
Nov 24 Python
PyCharm 2019.3发布增加了新功能一览
Dec 08 Python
Pytorch Tensor 输出为txt和mat格式方式
Jan 03 Python
Python urlencode和unquote函数使用实例解析
Mar 31 Python
PYTHON 使用 Pandas 删除某列指定值所在的行
Apr 28 Python
Python可视化神器pyecharts之绘制箱形图
Jul 07 Python
Pytorch Tensor的索引与切片例子
Aug 18 #Python
在PyTorch中Tensor的查找和筛选例子
Aug 18 #Python
对Pytorch神经网络初始化kaiming分布详解
Aug 18 #Python
pytorch中的embedding词向量的使用方法
Aug 18 #Python
Pytorch加载部分预训练模型的参数实例
Aug 18 #Python
在pytorch中查看可训练参数的例子
Aug 18 #Python
浅析PyTorch中nn.Module的使用
Aug 18 #Python
You might like
人族 Terran 魔法与科技
2020/03/14 星际争霸
php面向对象全攻略 (六)__set() __get() __isset() __unset()的用法
2009/09/30 PHP
PHP 基于文件头的文件类型验证类函数
2012/05/01 PHP
PHP实现通过strace定位故障原因的方法
2018/04/29 PHP
TP5(thinkPHP5)框架基于ajax与后台数据交互操作简单示例
2018/09/03 PHP
golang实现php里的serialize()和unserialize()序列和反序列方法详解
2018/10/30 PHP
jquery判断单个复选框是否被选中的代码
2009/09/03 Javascript
前端必备神器 Snap.svg 弹动效果
2014/11/10 Javascript
bootstrap改变按钮加载状态
2014/12/01 Javascript
jQuery插件EnPlaceholder实现输入框提示文字
2015/06/05 Javascript
javascript弹性运动效果简单实现方法
2016/01/08 Javascript
jQuery实现指定区域外单击关闭指定层的方法【经典】
2016/06/22 Javascript
JS实现滑动门效果的方法详解
2016/12/19 Javascript
在vue项目中引入highcharts图表的方法
2019/01/21 Javascript
vue+element-ui表格封装tag标签使用插槽
2020/06/18 Javascript
python中Apriori算法实现讲解
2017/12/10 Python
Python打印“菱形”星号代码方法
2018/02/05 Python
python 输出上个月的月末日期实例
2018/04/11 Python
Python3导入CSV文件的实例(跟Python2有些许的不同)
2018/06/22 Python
Python3 SSH远程连接服务器的方法示例
2018/12/29 Python
对python PLT中的image和skimage处理图片方法详解
2019/01/10 Python
Python QQBot库的QQ聊天机器人
2019/06/19 Python
tensorflow中tf.slice和tf.gather切片函数的使用
2020/01/19 Python
利用python实现平稳时间序列的建模方式
2020/06/03 Python
python3的pip路径在哪
2020/06/23 Python
HTML5新表单元素_动力节点Java学院整理
2017/07/12 HTML / CSS
HTML5新增属性data-*和js/jquery之间的交互及注意事项
2017/08/08 HTML / CSS
英国天然宝石首饰购买网站:Gemondo Jewellery
2018/10/23 全球购物
美国最大和最受信任的二手轮胎商店:Bestusedtires.com
2020/06/02 全球购物
电脑教师的教学自我评价
2013/11/26 职场文书
金融专业求职信
2014/08/05 职场文书
2014年督导工作总结
2014/11/19 职场文书
订货会主持词
2015/07/01 职场文书
护士旷工检讨书
2015/08/15 职场文书
2016幼儿园毕业感言
2015/12/08 职场文书
Pytest allure 命令行参数的使用
2021/04/18 Python