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格式化css文件的方法
Mar 10 Python
python实现支持目录FTP上传下载文件的方法
Jun 03 Python
django 使用 request 获取浏览器发送的参数示例代码
Jun 11 Python
Python编程中flask的简介与简单使用
Dec 28 Python
对python mayavi三维绘图的实现详解
Jan 08 Python
基于Python的Post请求数据爬取的方法详解
Jun 14 Python
Python利用WMI实现ping命令的例子
Aug 14 Python
浅谈django url请求与数据库连接池的共享问题
Aug 29 Python
Pytorch基本变量类型FloatTensor与Variable用法
Jan 08 Python
Python3开发实例之非关系型图数据库Neo4j安装方法及Python3连接操作Neo4j方法实例
Mar 18 Python
matplotlib图例legend语法及设置的方法
Jul 28 Python
PyCharm 2020.2下配置Anaconda环境的方法步骤
Sep 23 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中call_user_func_array()函数的用法演示
2012/02/05 PHP
JQuery中使用on方法绑定hover事件实例
2014/12/09 Javascript
JavaScript插件化开发教程(六)
2015/02/01 Javascript
jQuery+AJAX实现网页无刷新上传
2015/02/22 Javascript
jquery实现横向图片轮播特效代码分享
2015/11/19 Javascript
javascript数据结构之双链表插入排序实例详解
2015/11/25 Javascript
基于jquery实现智能提示控件intellSeach.js
2016/03/17 Javascript
Angularjs---项目搭建图文教程
2016/07/08 Javascript
功能强大的Bootstrap使用手册(一)
2016/08/02 Javascript
VueJS组件之间通过props交互及验证的方式
2017/09/04 Javascript
vue.js通过路由实现经典的三栏布局实例代码
2018/07/08 Javascript
浅谈在vue中使用mint-ui swipe遇到的问题
2018/09/27 Javascript
微信小程序实现限制用户转发功能的实例代码
2020/02/22 Javascript
js基于canvas实现时钟组件
2021/02/07 Javascript
python2.7 json 转换日期的处理的示例
2018/03/07 Python
python如何实现视频转代码视频
2019/06/17 Python
Djang的model创建的字段和参数详解
2019/07/27 Python
Python 堆叠柱状图绘制方法
2019/07/29 Python
python 实现手机自动拨打电话的方法(通话压力测试)
2019/08/08 Python
Python3 JSON编码解码方法详解
2019/09/06 Python
python集合常见运算案例解析
2019/10/17 Python
使用Python制作一个数据预处理小工具(多种操作一键完成)
2021/02/07 Python
JAVA代码查错题
2014/10/10 面试题
中国央视网签名寄语
2014/01/18 职场文书
倡议书格式
2014/04/14 职场文书
机械工程及自动化专业求职信
2014/09/03 职场文书
乡镇组织委员个人整改措施
2014/09/16 职场文书
教师四风对照检查材料思想汇报
2014/09/17 职场文书
2014年党的群众路线教育实践活动整改措施(个人版)
2014/09/25 职场文书
党员贯彻十八大精神思想汇报范文
2014/10/25 职场文书
画展邀请函
2015/01/31 职场文书
公司新员工欢迎词
2015/09/30 职场文书
学习经验交流会总结
2015/11/02 职场文书
Golang生成Excel文档的方法步骤
2021/06/09 Golang
浅谈Redis位图(Bitmap)及Redis二进制中的问题
2021/07/15 Redis
Java字符串逆序方法详情
2022/03/21 Java/Android