2

I'm looking for a way to expand the size of an image by adding 0 values to the right & lower edges of it. My initial plan is to use nn.padding to add the edge, until I encounter this error:

  File "/home/shared/virtualenv/dl-torch/lib/python3.7/site-packages/torch/nn/functional.py", line 2796, in pad
    assert len(pad) % 2 == 0, 'Padding length must be divisible by 2'
AssertionError: Padding length must be divisible by 2

It appears that torch tries to pad the image from both side! Is there an easy way to override this and fill the tensor into the upper-left side of another image?

tribbloid
  • 4,026
  • 14
  • 64
  • 103
  • You could create a tensor of zeros with single row and columns equal to that of original tensor, and then concatenate the original tensor with this one to get lower padding. Similarly, you can get right padding with a tensor of zeros that is a column vector. Of course, it's not single line code, but it is a way. Also, [this answer](https://stackoverflow.com/questions/53512281/concatenate-two-tensors-in-pytorch) does something similar to what you want. – akshayk07 Jun 01 '19 at 04:51
  • 1
    did you try `w.data = tensor` wrapped in `with torch.no_grad():`? – Charlie Parker Sep 17 '20 at 21:12
  • btw your title and details don't match at all. Dont do that. – Charlie Parker Sep 17 '20 at 21:12

3 Answers3

1

the only way I know is:

with torch.no_grad(): # assuming it's for init
  val = torch.distributions.MultivariateNormal(loc=zeros(2), scale=torch.eye(2))
  w.data =  val

but I doubt it's recommended.

Answering the title of the question.

Charlie Parker
  • 5,884
  • 57
  • 198
  • 323
0

With nn.ConstantPad2d, you can specify the number of padding elements in all four directions separately.

>>> t = torch.randn(2,3)
>>> t
tensor([[ 0.1254,  0.6358,  0.3243],
        [ 0.7005, -0.4931,  1.0582]])
>>> p = torch.nn.ConstantPad2d((0, 4, 0, 2), 0)
>>> p(t)
tensor([[ 0.1254,  0.6358,  0.3243,  0.0000,  0.0000,  0.0000,  0.0000],
        [ 0.7005, -0.4931,  1.0582,  0.0000,  0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000]])
Brennan Vincent
  • 10,736
  • 9
  • 32
  • 54
0

I had a similar problem and wanted to initialize a image tensor with a specific color. I solved it as follows:

Let X be a tensor of shape (h, w, dim) and let dim hold 3 values (r,g,b). If you want to initialize your tensor X with the rgb color 226, 169, 41 you could do something like:

index_0 = torch.tensor([0]) # 226
index_1 = torch.tensor([1]) #169
index_2 = torch.tensor([2]) #41

X.index_fill_(2, index_0, 226)
X.index_fill_(2, index_1, 169)
X.index_fill_(2, index_2, 41)
Joe Dawson
  • 95
  • 7