To be specific, I have a tensor of shape (300,300). I want to calculate the sum of the abs of difference of the current pixel and its surrounding 8 pixels.For example, if in the tensor T, T[1,2] = 1 and its surrounding 8 pixels are 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, and the sum value should be 1.8. So there can be another (300,300) tensor according to it. For loop can be used, but it’s way too slow. Any help would be greatly appreciated!!

# How can I calculate the abs of the difference between one value and its 8 surrounding values?

You can use torch fold function (https://pytorch.org/docs/stable/nn.html?highlight=fold#torch.nn.Fold) which allows you to slide a window with a custom function.

Thank you. I will try it!

The nn.Fold functions as conv2d, but I want the absolute difference value of each position. For example, [1, 2, 3] * [-1,2,-1].t() =0, but I want this to be 2. Is there any solution to it?