Extracting image patches given a coordinate list without looping

Hi!
I have an image with a long list of image indices. For each index-pair I would like to extract a 4x4 patch around that coordinate. At the moment I’ve solved it by looping (as can be seen in the code below).

I’m trying to speed up the calculations and was wondering if I could achieve the same thing without looping. Any ideas?

import torch

image = torch.rand((3, 200, 300))

# randomize indizes so that all patches are inside image
indy = torch.randint(196, (1000, )) + 1
indx = torch.randint(296, (1000, )) + 1

# extract patches for all images
all_patches = torch.zeros((1000, 3, 4, 4), dtype=image.dtype)
for j in [-1, 0, 1, 2]:
    for k in [-1, 0, 1, 2]:
        all_patches[:, :, j+1, k+1] = image[:, indy+j, indx+k].transpose(0, 1)

Thanks!

:grinning:
Found???