vaab / colour

Python color representations manipulation library (RGB, HSL, web, ...)
BSD 2-Clause "Simplified" License
322 stars 41 forks source link

Equality operator support #3

Closed kvesteri closed 11 years ago

kvesteri commented 11 years ago

It would be very nice if Color objects had equality operator support. Defining __eq__ and __ne__ methods in Color class would suffice:

def __eq__(self, other):
    return self.hex == other.hex

def __ne__(self, other):
    return self.hex != other.hex

This would allow the following syntax to evaluate as True:

Color('white') == Color('white')
vaab commented 11 years ago

This makes sense and seems useful. But isn't hex representation only one perspective ? This is a scenario playing with your proposition of the equality operator and internal representation (which is HSL).

>>> black_red = Color(hsl=(0, 0, 0))
>>> black_green = Color(hsl=(1./3, 0, 0))
>>> black_red == black_green
True
>>> for c in black_red, black_green:
...     c.saturation = 1
...     c.luminance = 0.5

>>> black_red == black_green
False
>>> black_red
<Color red>
>>> black_green
<Color green>

I'm not sure what we gain. Did you have some usage in mind to explicit what would be "very nice" if color had an equality operator support ? Would it loose it's niceness if any other representation would be used to compare color value instead of hex value ?

Just wanted to hear your ideas before integrating your code. Thank your for your interest !

vaab commented 11 years ago

For further reference on this topic, even if not used. Visual difference between two colors has been standardised. And thus, with a maximum difference, a near-perfect standardised way of comparing if two colors would be perceived as different(or equal) by a human eye would be implementable. More info:

http://en.wikipedia.org/wiki/Color_difference http://www.konicaminolta.com/instruments/knowledge/color/part5/03.html http://www.ece.rochester.edu/~gsharma/ciede2000/ciede2000noteCRNA.pdf

And there's a python module that is oriented towards all the mathematical aspect of color management:

https://github.com/gtaylor/python-colormath

Here's the delta_e doc: http://code.google.com/p/python-colormath/wiki/ColorObjects#delta_e%28%29

So colour could use them, but would introduce two dependencies as python-colormath depends also on numpy, which seems to be a high cost for a feature which might be anecdotical for most users of colour.

In the short term, I'm heading towards the RGB comparison because this is an equality for the computer display software and close to hardware implementation in most case. And it's a rough estimation of human visual difference that is better than HSL in the sense that it'll be able to tell that a black green and a black red are both the same color visually.