Pepe
Pepe

Reputation: 311

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]

Upvotes: 1

Views: 79

Answers (2)

Quang Hoang
Quang Hoang

Reputation: 150735

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])

Upvotes: 1

Mad Physicist
Mad Physicist

Reputation: 114310

If you are willing to have some zeros in your array, you can create a 4D array that tells you the difference between pixel [i, j] and in the original array[m, n] at location [i, j, m, n]. You will have zeros at along the diagonalwhere ai == m and j == n`, butyou can always mask that out or get rid of it in other ways:

img[..., None, None] - img[None, None, ...]

Upvotes: 0

Related Questions