# Slicing over 2 dimensions on a 3D Tensor

I have a 3 dimensional tensor that contains single channel images. For each image, I also have a pixel location (y, x). I want to grab a patch (say a patch of size 3x3) centered around the pixel location in this 3 dimensional tensor.

``````>>> d = torch.rand(4, 64, 64)
>>> yx = torch.tensor([(15, 21), (30, 59), (40, 5), (20, 25)])
>>> y, x = yx.T
>>> m = 1  # a patch of 3x3 centered around given pixel location

# loop through each image and stack the result
>>> out = torch.stack([di[yi - m : yi + m + 1, xi - m : xi + m + 1] \
for di, yi, xi in zip(d, y, x)])
>>> out.size()
torch.Size([4, 3, 3])
``````

Well, if I reduce the patch to size 1x1 pixel, which mean only the pixel and no neighbors pixels, then I could simply use the following:

``````>>> loc = (range(4), y, x)
>>> out = d[loc]
>>> out.size()
torch.Size([4])
``````

However, I actually need a patch of size more than 1x1. I tried using the same approach but no success:

``````>>> x_slice = slice(x - m, x + m + 1)
>>> y_slice = slice(y - m, y + m + 1)
>>> d[(range(4), y_slice, x_slice)]
TypeError: only integer tensors of a single element can be converted to an index
``````

My approach applying `torch.stack( ... )` uses a `for` loop. I am wondering if there is a better PyTorch way of doing the same.

PS: In this case, please assume that input pixel locations are never on the edges. In other words, it is always possible to grab a patch of a given size!