How can I get an unaligned tensor from a large one efficiently?
The pseudo-code is shown as follow (it can not work in pytorch):
x = torch.rand((3,1,6,6), requires_grad=True) # [batch_size, channel, w, h]
left_index = torch.randint(0,4,(3,))
right_index = left_index + 2
bottom_index = torch.randint(0,4,(3,))
top_index = bottom_index + 2
new_x = x[:,:,left_index:right_index, bottom_index:top_index]

that means, for the i-th image, we want to get a small tensor using slice
(i, :, left_index[i]: right_index[i], bottom_index[i]: top_index[i])
Of course, if I write a for-loop code enumerating through all the images and stacking the results, I can obtain the wanted small tensor.
However, I think “for-loop+stacking” algorithm takes time, and I want a more efficient method. Please give me some advice. Thank you!