Overlap two tensors of different size based on an offset in PyTorch
I have the following structure:
torch.Size([channels, width, height])

Let's say I have a tensor a
torch.Size([4, 512, 512])

And tensor b
torch.Size([4, 100, 100])

What I would like to do is to create a tensor c that is the result of &quot;placing&quot; tensor b on an arbitrary (width, height) coordinate offset of tensor a. For example, let's say I would like to place tensor b on (300,100) of tensor a
So for tensor a's width between the 300-400 position, the values on tensor a should be replaced by the 100 values of tensor b width.
For tensor a's height between the 100-200 position, the values of tensor a should be replaced by the 100 values of tensor b height.
I would also like to choose for which channels I want to do this substitution and for which channels I would keep tensor a's value
(PS: The image is just an easy to illustrate example, but I would like to do it in a more generalisable way, so I'm no interested in converting to PIL, using PIL.paste and back to tensor but I would like to do all operations directly with)

This function would be fragile without a bunch of pre-conditions to catch for size mismatches, but I think this is basically what you're describing:
def place(a: torch.Tensor, b: torch.Tensor, 
          height: int, width: int, 
          channels: list[int]) -&gt; torch.Tensor:
    &quot;&quot;&quot;create a tensor ``c`` that is the result of 
    &quot;placing&quot; tensor ``b`` on an arbitrary (height, width) 
    coordinate offset of tensor ``a``,
    for only the specified ``channels``
    &quot;&quot;&quot;
    channels_b, height_b, width_b  = b.size()
    c = a.clone().detach()
    for channel in channels:
        c[channel, 
          height:height + height_b,
          width:width + width_b] = b[channel]
    return c

