Search code examples
pythonimagenumpyimage-processingpixel

Compute image pixel differences in efficient way


Say I have a 24 x 24 image as a numpy array.

I want to compute the pixel differences between each pixel and all the other pixels in the image, excluding that pixel. That will give me (24 * 24) * (24 * 24 -1) values.

How do I do this outside of a loop and in an efficient manner?

Example:

Array of image:

[[1,5],
[8,3]]

Differences:

Pixel 1 (Value = 1) : [-4,-7,-2]
Pixel 2 (Value = 5) :  [4,-3,2]
Pixel 3 (Value = 8): [7,3,5]
Pixel 4 (Value = 3):[2,-2,-5]

End Result:

[-4, -7, -2, 4, -3, 2, 7, 3, 5, 2, -2, -5]

Solution

  • Here's my approach:

    ret = img.ravel()
    ret = ret[:,None] - ret
    
    mask = np.arange(len(ret)) != np.arange(len(ret))[:,None]
    # masking
    ret[np.where(mask)]
    

    Output:

    array([-4, -7, -2,  4, -3,  2,  7,  3,  5,  2, -2, -5])