Artyer
Artyer

Reputation: 40891

PIL remove colour mixing between colour regions

I have images with very few colours in them. (5 different colours max, and all are quite distinct.)

At the boundaries of the regions between colours, there is a (usually single pixel wide) line of a mix between these colours. How can I remove this?

I do manipulation with them as a numpy array afterwards anyways, so if this can be achieved with a numpy array, that works too.

For example, this image:

10*10 white, 1*10 (.25, .25, .25) and 10*10 black

Which is made from this array:

image = np.append(
    np.append(np.ones((10, 10, 3)), np.ones((1, 10, 3)) / 5., axis=0),
    np.zeros((10, 10, 3)), axis=0
)

# Or a 10 * 10 white (0, 0, 0) region with a 1 * 10 line of (0.2, 0.2, 0.2) pixels
# underneath and a 10 * 10 black (1, 1, 1) region underneath that.

# Expected result:
expected = np.append(np.ones((10, 10, 3)), np.zeros((11, 10, 3)), axis=0)

I would like a function that converts that 1 * 10 line of grey pixels into black, as it is closer to black.

Upvotes: 1

Views: 50

Answers (1)

Mark Ransom
Mark Ransom

Reputation: 308432

You can use Image.quantize to force all colors to match your palette. This changes the mode of your image to P, convert it back to RGB when you're done.

Upvotes: 2

Related Questions