tribbloid
tribbloid

Reputation: 3838

In pytorch, how to fill a tensor with another tensor?

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?

Upvotes: 2

Views: 5542

Answers (3)

Joe Dawson
Joe Dawson

Reputation: 95

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)

Upvotes: 0

Charlie Parker
Charlie Parker

Reputation: 5201

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.

Upvotes: 1

Brennan Vincent
Brennan Vincent

Reputation: 10666

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]])

Upvotes: 0

Related Questions