【问题标题】:Pad a Tensor in Torch在 Torch 中填充一个张量
【发布时间】:2016-03-21 21:57:27
【问题描述】:

我在 Torch 张量中有一个 100x100 像素的图像,我想实现“缩小”转换。如何使用 Torch Image 工具箱(或其他)实现这一目标?

我已经通过简单地使用 image.crop 和 image.resize 实现了“放大”。

在 Matlab 中,我会计算图像的平均灰度,用该颜色填充数组 n 个像素(保持原始图像居中),然后将大小调整为 100x100 像素。 Torch 有“pad Tensor”功能吗?

谢谢!

【问题讨论】:

    标签: image image-processing lua transform torch


    【解决方案1】:

    Torch 有“pad Tensor”功能吗?

    一种可能性是使用来自torch/nnnn.Padding 模块,例如:

    require 'image'
    require 'nn'
    
    local x = image.lena()
    
    local pad  = 64
    local pix  = 0
    local ndim = x:dim()
    
    local s = nn.Sequential()
      :add(nn.Padding(ndim-1,  pad, ndim, pix))
      :add(nn.Padding(ndim-1, -pad, ndim, pix))
      :add(nn.Padding(ndim,    pad, ndim, pix))
      :add(nn.Padding(ndim,   -pad, ndim, pix))
    
    local y = s:forward(x)
    
    image.display(y) -- this requires qlua
    

    更新

    可以看出implementation padding 是通过以下方式获得的:

    1. 分配预期大小的输出张量后填充填充填充颜色,
    2. 感谢narrow,用原始值填充输入张量对应的区域。

    玩具示例:

    require 'torch'
    
    local input  = torch.zeros(2, 5)
    local dim    = 2 -- target dimension for padding
    local pad    = 3 -- amount of padding
    local pix    = 1 -- pixel value (color)
    
    -- (1) compute the expected size post-padding, allocate a large enough tensor
    --     and fill with expected color
    local size   = input:size()
    size[dim]    = size[dim] + pad
    local output = input.new():resize(size):fill(pix)
    
    -- (2) fill the original area with original values
    local area   = output:narrow(dim, 1, input:size(dim)):copy(input)
    

    这给出了输出:

    0  0  0  0  0  1  1  1
    0  0  0  0  0  1  1  1
    [torch.DoubleTensor of size 2x8]
    

    对于特定的零填充,还有其他方便的可能性,例如:

    【讨论】:

    • 谢谢老哥,我试试。否则,我怀疑我可以创建一个填充大小的新张量,复制数据,然后调整它的大小。
    猜你喜欢
    • 2019-12-28
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 2023-04-02
    • 2016-01-19
    • 2016-03-17
    • 2016-07-02
    • 1970-01-01
    相关资源
    最近更新 更多