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 22 Python
Python内置函数OCT详解
Nov 09 Python
python一键升级所有pip package的方法
Jan 16 Python
python查询mysql,返回json的实例
Mar 26 Python
python人民币小写转大写辅助工具
Jun 20 Python
Python内存读写操作示例
Jul 18 Python
Python脚本修改阿里云的访问控制列表的方法
Mar 08 Python
python数据化运营的重要意义
Nov 25 Python
python读取与处理netcdf数据方式
Feb 14 Python
在python中使用pymysql往mysql数据库中插入(insert)数据实例
Mar 02 Python
Django调用支付宝接口代码实例详解
Apr 04 Python
基于PyInstaller各参数的含义说明
Mar 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
PHP实现Socket服务器的代码
2008/04/03 PHP
PHP游戏编程25个脚本代码
2011/02/08 PHP
php ci框架验证码实例分析
2013/06/26 PHP
PHP使用静态方法的几个注意事项
2014/09/16 PHP
ThinkPHP框架实现的微信支付接口开发完整示例
2019/04/10 PHP
Laravel Validator 实现两个或多个字段联合索引唯一
2019/05/08 PHP
php中加密解密DES类的简单使用方法示例
2020/03/26 PHP
Laravel框架源码解析之入口文件原理分析
2020/05/14 PHP
表单JS弹出填写提示效果代码
2011/04/16 Javascript
firefox下jQuery UI Autocomplete 1.8.*中文输入修正方法
2012/09/19 Javascript
网页加载时页面显示进度条加载完成之后显示网页内容
2012/12/23 Javascript
jQuery中nextUntil()方法用法实例
2015/01/07 Javascript
图文详解Heap Sort堆排序算法及JavaScript的代码实现
2016/05/04 Javascript
js注入 黑客之路必备!
2016/09/14 Javascript
使用ReactJS实现tab页切换、菜单栏切换、手风琴切换和进度条效果
2016/10/17 Javascript
Node.js中process模块常用的属性和方法
2016/12/13 Javascript
JS去除重复并统计数量的实现方法
2016/12/15 Javascript
详解Vue.js项目API、Router配置拆分实践
2018/03/16 Javascript
使用Angular CLI快速创建Angular项目的一些基本概念和写法小结
2018/04/22 Javascript
解决vue2.0路由跳转未匹配相应用路由避免出现空白页面的问题
2018/08/24 Javascript
React 路由懒加载的几种实现方案
2018/10/23 Javascript
Vue Cli3 打包配置并自动忽略console.log语句的方法
2020/04/23 Javascript
python绘图库Matplotlib的安装
2014/07/03 Python
jupyter安装小结
2016/03/13 Python
Python基于matplotlib绘制栈式直方图的方法示例
2017/08/09 Python
python+matplotlib实现礼盒柱状图实例代码
2018/01/16 Python
Python使用Windows API创建窗口示例【基于win32gui模块】
2018/05/09 Python
PyCharm-错误-找不到指定文件python.exe的解决方法
2019/07/01 Python
使用pandas读取文件的实现
2019/07/31 Python
字符串str除首尾字符外的其他字符按升序排列
2013/03/08 面试题
党员承诺书内容
2014/03/26 职场文书
环保建议书300字
2014/05/14 职场文书
2014年小学德育工作总结
2014/12/05 职场文书
公安机关起诉意见书
2015/05/20 职场文书
2016年乡镇综治宣传月活动总结
2016/03/16 职场文书
关于MySQL中的 like操作符详情
2021/11/17 MySQL