nathancahill
nathancahill

Reputation: 10850

Python PIL compare colors

I have an image with a noisy background like this (blown-up, each square is a pixel). I'm trying to normalize the black background so that I can replace the color entirely.

This is what I'm thinking (psuedo code):

for pixel in image:
    if is_similar(pixel, (0, 0, 0), threshold):
        pixel = (0, 0, 0)

What sort of function would allow me to compare two color values to match within a certain threshold?

Upvotes: 4

Views: 5479

Answers (1)

nathancahill
nathancahill

Reputation: 10850

I ended up using the perceived luminance formula from this answer. It worked perfectly.

THRESHOLD = 18

def luminance(pixel):
    return (0.299 * pixel[0] + 0.587 * pixel[1] + 0.114 * pixel[2])


def is_similar(pixel_a, pixel_b, threshold):
    return abs(luminance(pixel_a) - luminance(pixel_b)) < threshold


width, height = img.size
pixels = img.load()

for x in range(width):
    for y in range(height):
        if is_similar(pixels[x, y], (0, 0, 0), THRESHOLD):
            pixels[x, y] = (0, 0, 0)

Upvotes: 9

Related Questions