Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 368
nathancahill Avatar asked Oct 19 '25 19:10

nathancahill


1 Answers

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)
like image 121
nathancahill Avatar answered Oct 22 '25 08:10

nathancahill