Skip to content Skip to sidebar Skip to footer

Compare Current Pixel Value With The Previous One On Numpy Array

Is possible to implement this image filtering process in numpy array ? I need to check if the pixel in the previous column and previous row is differente of the current pixel. widt

Solution 1:

Here's one approach. Take an example image:

Render of Utah teapot model by Martin Newell

You didn't say where your orig_bin came from, so I've used scipy.misc.imread:

from scipy.misc import imread, imsaveimg= imread('input.png')

First, create a mask for pixels that are different from the pixel above (this uses an idea from Bi Rico's answer):

up   = (img[1:,1:] != img[:-1,1:]).any(axis=2)

Note that imread loads images in row-major order, so the first NumPy axis is the vertical axis. See "Multidimensional Array Indexing Order Issues" for an explanation.

Similarly, create a mask for pixels that are different from the pixel to the left:

left = (img[1:,1:] != img[1:,:-1]).any(axis=2)

Combine these to get a mask for pixels that are different to either the pixel above or left:

mask = numpy.zeros(img.shape[:2], dtype=bool)
mask[1:,1:] = left | up

Create a black output image of the right size; then set the mask to white:

output = numpy.zeros(img.shape)
output[mask] = (255, 255, 255)
imsave('output.png', output)

And here's the result:

Output white

or if you want the colours to be the other way round, invert the mask:

output[~mask] = (255, 255, 255)

Output black

Solution 2:

You want something like:

change = (pixels[1:, 1:] != pixels[1:, :-1]) | (pixels[1:, 1:] != pixels[:-1, 1:])

This will be binary (True, False), you'll need to multiply it by 255 if you want your result to be 0/255. You also might need to run and any on the last dimension if you array is (x, y, 3).

There are other ways you could re-cast this problem, for example a convolution with [1, -1] might get you most of the way there.

Post a Comment for "Compare Current Pixel Value With The Previous One On Numpy Array"