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删除windows垃圾文件的方法
Jul 14 Python
Pandas探索之高性能函数eval和query解析
Oct 28 Python
Python使用Scrapy保存控制台信息到文本解析
Dec 27 Python
python爬取拉勾网职位数据的方法
Jan 24 Python
python分治法求二维数组局部峰值方法
Apr 03 Python
Python实现时钟显示效果思路详解
Apr 11 Python
Python count函数使用方法实例解析
Mar 23 Python
python数据库操作mysql:pymysql、sqlalchemy常见用法详解
Mar 30 Python
Python 将 QQ 好友头像生成祝福语的实现代码
May 03 Python
Django model class Meta原理解析
Nov 14 Python
python爬取某网站原图作为壁纸
Jun 02 Python
Python FuzzyWuzzy实现模糊匹配
Apr 28 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
ThinkPHP中URL路径访问与模块控制器之间的关系
2014/08/23 PHP
PHP实现链式操作的核心思想
2015/06/23 PHP
YiiFramework入门知识点总结(图文教程)
2015/12/28 PHP
PHP会员找回密码功能的简单实现
2016/09/05 PHP
PHP-FPM 的管理和配置详解
2019/02/17 PHP
PHP使用ActiveMQ实现消息队列的方法详解
2019/05/31 PHP
sencha touch 模仿tabpanel导航栏TabBar的实例代码
2013/10/24 Javascript
checkbox全选所涉及到的知识点介绍
2013/12/31 Javascript
使用纯javascript实现放大镜效果
2015/03/18 Javascript
JS替换字符串中空格方法
2015/04/17 Javascript
jQuery实现监控页面所有ajax请求的方法
2015/12/10 Javascript
JavaScript实现公历转农历功能示例
2017/02/13 Javascript
Bootstrap 3浏览器兼容性问题及解决方案
2017/04/11 Javascript
解决vue组件中使用v-for出现告警问题及v for指令介绍
2017/11/11 Javascript
js实现点击按钮复制文本功能
2020/07/20 Javascript
jQuery实现图片简单轮播功能示例
2018/08/13 jQuery
js中比较两个对象是否相同的方法示例
2019/09/02 Javascript
keep-Alive搭配vue-router实现缓存页面效果的示例代码
2020/06/24 Javascript
js异步接口并发数量控制的方法示例
2020/11/22 Javascript
HTML元素拖拽功能实现的完整实例
2020/12/04 Javascript
[00:43]拉比克至宝魔导师密钥展示
2018/12/20 DOTA
Python中的anydbm模版和shelve模版使用指南
2015/07/09 Python
详解使用 pyenv 管理多个版本 python 环境
2017/10/19 Python
python实现推箱子游戏
2020/03/25 Python
在python下使用tensorflow判断是否存在文件夹的实例
2019/06/10 Python
python3 deque 双向队列创建与使用方法分析
2020/03/24 Python
HTML5 Web存储方式的localStorage和sessionStorage进行数据本地存储案例应用
2012/12/09 HTML / CSS
canvas绘制视频封面的方法
2018/02/05 HTML / CSS
预备党员政审材料
2014/02/04 职场文书
会计核算科岗位职责
2014/03/19 职场文书
2016关于军训的心得体会
2016/01/11 职场文书
2016年第二十届“母亲节暨幸福工程救助贫困母亲活动日”活动总结
2016/04/06 职场文书
Python使用protobuf序列化和反序列化的实现
2021/05/19 Python
logback 实现给变量指定默认值
2021/08/30 Java/Android
选购到合适的激光打印机
2022/04/21 数码科技
python实现学生信息管理系统(面向对象)
2022/06/05 Python