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对Excel中的特定数据提取并写入新表的方法
Jun 14 Python
python顺序的读取文件夹下名称有序的文件方法
Jul 11 Python
python实现Dijkstra静态寻路算法
Jan 17 Python
Pandas读写CSV文件的方法示例
Mar 27 Python
python通过paramiko复制远程文件及文件目录到本地
Apr 30 Python
连接pandas以及数组转pandas的方法
Jun 28 Python
python实现两个经纬度点之间的距离和方位角的方法
Jul 05 Python
python安装本地whl的实例步骤
Oct 12 Python
Python递归及尾递归优化操作实例分析
Feb 01 Python
对python中arange()和linspace()的区别说明
May 03 Python
python使用正则表达式匹配txt特定字符串(有换行)
Dec 09 Python
用Python爬取各大高校并可视化帮弟弟选大学,弟弟直呼牛X
Jun 11 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
怎么在Windows系统中搭建php环境
2013/08/31 PHP
PHP 之 写时复制介绍(Copy On Write)
2014/05/13 PHP
CodeIgniter连贯操作的底层原理分析
2016/05/17 PHP
PHP5.5基于mysqli连接MySQL数据库和读取数据操作实例详解
2019/02/16 PHP
javascript 另一种图片滚动切换效果思路
2012/04/20 Javascript
JS简单实现元素复制示例附图
2013/11/19 Javascript
jquery.post用法关于type设置问题补充
2014/01/03 Javascript
nodejs爬虫抓取数据之编码问题
2015/07/03 NodeJs
使用jquery实现鼠标滑过弹出更多相关信息层附源码下载
2015/11/23 Javascript
全面了解构造函数继承关键apply call
2016/07/26 Javascript
KnockoutJS 3.X API 第四章之表单textInput、hasFocus、checked绑定
2016/10/11 Javascript
AngularJS入门教程之MVC架构实例分析
2016/11/01 Javascript
js实现模糊匹配功能
2017/02/15 Javascript
基于layer.js实现收货地址弹框选择然后返回相应的地址信息
2017/05/26 Javascript
jquery插件开发之选项卡制作详解
2017/08/30 jQuery
最新Javascript程序员面试试题和解题方法
2017/11/23 Javascript
分析JavaScript数组操作难点
2017/12/18 Javascript
element-ui 表格实现单元格可编辑的示例
2018/02/26 Javascript
微信小程序实现多选框全选与取消全选功能示例
2019/05/14 Javascript
Vue CLI项目 axios模块前后端交互的使用(类似ajax提交)
2019/09/01 Javascript
pycharm 使用心得(七)一些实用功能介绍
2014/06/06 Python
Python3.x版本中新的字符串格式化方法
2015/04/24 Python
对python中的高效迭代器函数详解
2018/10/18 Python
Python通过2种方法输出带颜色字体
2020/03/02 Python
Python urllib库如何添加headers过程解析
2020/10/05 Python
Get The Label中文官网:英国运动时尚购物平台
2017/04/19 全球购物
某IT外企面试题-二分法求方程!看看大家的C++功底
2015/07/04 面试题
设置器与访问器的定义以及各自特点
2016/01/08 面试题
艺术设计专业个人求职信范文
2013/12/11 职场文书
上学迟到的检讨书
2014/01/11 职场文书
公司合作意向书
2014/04/01 职场文书
法人代表任命书范本
2014/06/05 职场文书
周恩来的四个昼夜观后感
2015/06/03 职场文书
今日说法观后感
2015/06/08 职场文书
详解Python+OpenCV绘制灰度直方图
2022/03/22 Python
Python万能模板案例之matplotlib绘制甘特图
2022/04/13 Python