3

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?

nathancahill
  • 10,452
  • 9
  • 51
  • 91
  • 1
    Take a look at http://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color , using a luminance formula essentially gives you each pixel's value in grayscale thus allowing you to compare your pixels against a threshold in only 1 dimension. – Darren Ringer Nov 05 '14 at 19:58
  • 2
    Check out Wikipedia's [Color Difference](http://en.wikipedia.org/wiki/Color_difference) article for a few approaches on determining how similar two colors are. The simplest answer is: treat each color as a three-dimensional coordinate, and use the Pythagorean Formula to find the distance between them. – Kevin Nov 05 '14 at 20:07

1 Answers1

8

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)
Community
  • 1
  • 1
nathancahill
  • 10,452
  • 9
  • 51
  • 91