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实现根据月份和日期得到星座的方法
Mar 27 Python
python模拟enum枚举类型的方法小结
Apr 30 Python
Pytorch入门之mnist分类实例
Apr 14 Python
python批量获取html内body内容的实例
Jan 02 Python
python3 中的字符串(单引号、双引号、三引号)以及字符串与数字的运算
Jul 18 Python
Python的bit_length函数来二进制的位数方法
Aug 27 Python
python使用pip安装SciPy、SymPy、matplotlib教程
Nov 20 Python
基于python+selenium的二次封装的实现
Jan 06 Python
Tensorflow限制CPU个数实例
Feb 06 Python
浅谈Python中的异常和JSON读写数据的实现
Feb 27 Python
python 基于opencv实现图像增强
Dec 23 Python
Python中Matplotlib的点、线形状、颜色以及绘制散点图
Apr 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
PHP判断远程url是否有效的几种方法小结
2011/10/08 PHP
php使用smtp发送支持附件的邮件示例
2014/04/13 PHP
PHP输出九九乘法表代码实例
2015/03/27 PHP
Laravel 5框架学习之路由、控制器和视图简介
2015/04/07 PHP
百度工程师讲PHP函数的实现原理及性能分析(三)
2015/05/13 PHP
php判断用户是否关注微信公众号
2016/07/22 PHP
再谈javascript面向对象编程
2012/03/18 Javascript
js点击更换背景颜色或图片的实例代码
2013/06/25 Javascript
浅析document.createDocumentFragment()与js效率
2013/07/08 Javascript
javascript字母大小写转换的4个函数详解
2014/05/09 Javascript
百度判断手机终端并自动跳转js代码及使用实例
2014/06/11 Javascript
JQuery球队选择实例
2015/05/18 Javascript
javascript实现连续赋值
2015/08/10 Javascript
js获取上传文件的绝对路径实现方法
2016/08/02 Javascript
利用transition实现文字上下抖动的效果
2017/01/21 Javascript
利用Angular.js编写公共提示模块的方法教程
2017/05/28 Javascript
关于echarts在节点显示动态数据及添加提示文本所遇到的问题
2018/04/20 Javascript
NodeJS 文件夹拷贝以及删除功能
2019/09/03 NodeJs
Python中exit、return、sys.exit()等使用实例和区别
2015/05/28 Python
Python装饰器用法示例小结
2018/02/11 Python
python使用jieba实现中文分词去停用词方法示例
2018/03/11 Python
机器学习之KNN算法原理及Python实现方法详解
2018/07/09 Python
如何利用Anaconda配置简单的Python环境
2019/06/24 Python
Python基础之函数基本用法与进阶详解
2020/01/02 Python
解决 jupyter notebook 回车换两行问题
2020/04/15 Python
python简单实现最大似然估计&amp;scipy库的使用详解
2020/04/15 Python
python实现简单贪吃蛇游戏
2020/09/29 Python
10分钟入门CSS3 Animation
2018/12/25 HTML / CSS
澳大利亚药房在线:ThePharmacy
2017/10/04 全球购物
日本必酷网络直营店:Biccamera
2019/03/23 全球购物
size?爱尔兰官方网站:英国伦敦的球鞋精品店
2019/03/31 全球购物
花店创业计划书范文
2014/02/07 职场文书
《放飞蜻蜓》教学反思
2014/04/27 职场文书
校园绿化美化方案
2014/06/08 职场文书
2015年小学体育教师工作总结
2015/10/23 职场文书
vue首次渲染全过程
2021/04/21 Vue.js