Compare Current Pixel Value With The Previous One On Numpy Array
Solution 1:
Here's one approach. Take an example image:
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:
or if you want the colours to be the other way round, invert the mask:
output[~mask] = (255, 255, 255)
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"