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脚本实现下载合并SAE日志
Feb 10 Python
Python实现简单的代理服务器
Jul 25 Python
Python打印输出数组中全部元素
Mar 13 Python
pytorch训练imagenet分类的方法
Jul 27 Python
Django Channels 实现点对点实时聊天和消息推送功能
Jul 17 Python
Python搭建代理IP池实现存储IP的方法
Oct 27 Python
pycharm激活码快速激活及使用步骤
Mar 12 Python
python实现猜单词游戏
May 22 Python
Python中有几个关键字
Jun 04 Python
python:HDF和CSV存储优劣对比分析
Jun 08 Python
基于python实现ROC曲线绘制广场解析
Jun 28 Python
从np.random.normal()到正态分布的拟合操作
Jun 02 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
如何写php程序?
2006/12/08 PHP
PHP删除目录及目录下所有文件的方法详解
2013/06/06 PHP
php json与xml序列化/反序列化
2013/10/28 PHP
PHP制作万年历
2015/01/07 PHP
php操作xml入门之xml标签的属性分析
2015/01/23 PHP
PHP中的use关键字及文件的加载详解
2016/11/28 PHP
PHP经典实用正则表达式小结
2017/05/04 PHP
解决FireFox下[使用event很麻烦]的问题
2006/11/26 Javascript
Javascript 遮罩层和加载效果代码
2013/08/01 Javascript
JS中字符串trim()使用示例
2015/05/26 Javascript
SpringMVC框架下JQuery传递并解析Json格式的数据是如何实现的
2015/12/10 Javascript
jQuery UI库中dialog对话框功能使用全解析
2016/04/23 Javascript
jQuery表单验证简单示例
2016/10/17 Javascript
jquery 判断div show的状态实例
2016/12/03 Javascript
AngularJS路由切换实现方法分析
2017/03/17 Javascript
vscode中vue-cli项目es-lint的配置方法
2018/07/30 Javascript
详解Vue改变数组中对象的属性不重新渲染View的解决方案
2018/09/21 Javascript
Nodejs对postgresql基本操作的封装方法
2019/02/20 NodeJs
vue单页应用的内存泄露定位和修复问题小结
2019/08/02 Javascript
vuex实现像调用模板方法一样调用Mutations方法
2019/11/06 Javascript
通过angular CDK实现页面元素拖放的步骤详解
2020/07/01 Javascript
[13:38]2015国际邀请赛中国战队出征仪式
2015/05/29 DOTA
python中matplotlib实现最小二乘法拟合的过程详解
2017/07/11 Python
pyqt5自定义信号实例解析
2018/01/31 Python
python如何统计代码运行的时长
2019/07/24 Python
python print 格式化输出,动态指定长度的实现
2020/04/12 Python
Python基于pyjnius库实现访问java类
2020/07/31 Python
如何使用 Python 读取文件和照片的创建日期
2020/09/05 Python
基于PyTorch中view的用法说明
2021/03/03 Python
html5实现的便签特效(实战分享)
2013/11/29 HTML / CSS
快速创建 HTML5 Canvas 电信网络拓扑图的示例代码
2018/03/21 HTML / CSS
美国最大的宠物用品零售商:PetSmart
2016/11/14 全球购物
斯凯奇新西兰官网:SKECHERS新西兰
2018/02/22 全球购物
检察官就职演讲稿
2014/01/13 职场文书
企业宗旨标语
2014/06/10 职场文书
利用javaScript处理常用事件详解
2021/04/14 Javascript