[Image-SIG] Removing specific range of colors from scanned image

Scott David Daniels Scott.Daniels at Acm.Org
Tue Apr 28 20:35:59 CEST 2009

Eduardo Ismael wrote:
> Thank you very much for your feedback, John. It works wonders!!!
> Would you please make comments on what I could do to improve the code below?

> def distance (a, b):
>     return ((a[0]- b[0])** 2 + (a[1]- b[1])** 2 + (a[-1]- b[-1]) ** 2) 
> ** 0.5
The square root here is not free.  A standard trick is to realize that,
if you are going to test distance(...) < constant, you can, instead,
calculate distance_squared:
     def distance_squared(a, b):
         return sum((ac -  bc)**2 for ac, bc in zip(a, b))
and compare it to constant_squared.
So that your code later:
> for x in range(width):
>     for y in range(height):
>         if distance_squared(pixels[x, y], blue) < 2500:
>             pixels[x, y] = (255, 255, 255)

While this trick won't make that code sufficiently fast,
it is a good trick to know.

> I guess I got the main idea, but please tell me if there is anything I 
> could do to improve it. Also, I don't think I followed your advice on 
> "processing at the image level rather than by looping over pixels" Would 
> you correct it for me?
> By the way, thanks to your explanation of the color cube approach, I was 
> able to come up with this other script:
> ... Also, If not RGB, which color space would be the best?

HLS (Hue, Lightness, Saturation) is an interesting space, with the hue
picked out for you (as long as you avoid the extrema in lightness and
the near-zero saturation points).

--Scott David Daniels
Scott.Daniels at Acm.Org

More information about the Image-SIG mailing list