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创建和使用字典实例详解
Nov 01 Python
python文件操作整理汇总
Oct 21 Python
python转换字符串为摩尔斯电码的方法
Jul 06 Python
Python判断列表是否已排序的各种方法及其性能分析
Jun 20 Python
使用Python进行QQ批量登录的实例代码
Jun 11 Python
Flask实现跨域请求的处理方法
Sep 27 Python
python实现对任意大小图片均匀切割的示例
Dec 05 Python
Python学习笔记之For循环用法详解
Aug 14 Python
Python对称的二叉树多种思路实现方法
Feb 28 Python
python GUI库图形界面开发之PyQt5信号与槽事件处理机制详细介绍与实例解析
Mar 08 Python
Python内存映射文件读写方式
Apr 24 Python
Python如何转换字符串大小写
Jun 04 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
PHILIPS L4X25T电路分析和打理
2021/03/02 无线电
Apache2中实现多网站域名绑定的实现方法
2011/06/01 PHP
Php Ctemplate引擎开发相关内容
2012/03/03 PHP
浅析php静态方法与非静态方法的用法区别
2016/05/17 PHP
用示例说明filter()与find()的用法以及children()与find()的区别分析
2013/04/26 Javascript
JQ获取动态加载的图片大小的正确方法分享
2013/11/08 Javascript
Javascript连接多个数组不用concat来解决
2014/03/24 Javascript
JS应用正则表达式转换大小写示例
2014/09/18 Javascript
深入理解JavaScript系列(38):设计模式之职责链模式详解
2015/03/04 Javascript
用iframe实现不刷新整个页面上传图片的实例
2016/11/18 Javascript
AngularJS Select(选择框)使用详解
2017/01/18 Javascript
Angularjs中的ui-bootstrap的使用教程
2017/02/19 Javascript
vue Render中slots的使用的实例代码
2017/07/19 Javascript
Vue数据双向绑定的深入探究
2018/11/27 Javascript
javascript实现视频弹幕效果(两个版本)
2019/11/28 Javascript
vue data变量相互赋值后被实时同步的解决步骤
2020/08/05 Javascript
JS实现手风琴特效
2020/11/08 Javascript
vue基于Echarts的拖拽数据可视化功能实现
2020/12/04 Vue.js
详解JavaScript中的this指向问题
2021/02/05 Javascript
[02:42]完美大师赛主赛事淘汰赛第三日观众采访
2017/11/25 DOTA
[04:14]从西雅图到上海——玩家自制DOTA2主题歌曲应援TI9
2019/07/11 DOTA
Ubuntu 16.04 LTS中源码安装Python 3.6.0的方法教程
2016/12/27 Python
python进阶_浅谈面向对象进阶
2017/08/17 Python
Python爬虫包BeautifulSoup简介与安装(一)
2018/06/17 Python
Python3对称加密算法AES、DES3实例详解
2018/12/06 Python
python 动态生成变量名以及动态获取变量的变量名方法
2019/01/20 Python
python 三种方法实现对Excel表格的读写
2020/11/19 Python
MyFrenchPharma中文网:最大的法国药妆平台
2016/10/07 全球购物
有个性的自我评价范文
2013/11/15 职场文书
外贸业务员岗位职责
2013/11/24 职场文书
2014年小学元旦活动方案
2014/02/12 职场文书
《音乐之都维也纳》教学反思
2014/04/16 职场文书
节能环保家庭事迹材料
2014/08/27 职场文书
材料物理专业求职信
2014/09/01 职场文书
优秀教师个人材料
2014/12/15 职场文书
中学教代会开幕词
2016/03/04 职场文书