h3.
h3.

Reputation: 11078

hex <-> RGB <-> HSV Color space conversion with Python

For this project I use Python's colorsys to convert RGB to HSV vice versa to be able to manipulate saturation and lightness, but I noticed that some colors yields bogus results.

For example, if I take any primary colors there's no problem:

However if I chose a random RGB color and convert it to HSV, I sometime gets bogus results.

Sometimes these bogus results occurs when I increase or decrease the lightness or the saturation of a color.

In this example lightness 10%, 20% and saturation 100% are bogus:

I'm not quite sure why it happens nor how I should fix this ..

Upvotes: 0

Views: 3951

Answers (1)

Ned Batchelder
Ned Batchelder

Reputation: 376052

The problem is in your dec2hex code:

def dec2hex(d):
    """return a two character hexadecimal string representation of integer d"""
    r = "%X" % d
    return r if len(r) > 1 else r+r

When your value is less than 16, you're duplicating it to get the value, in other words, multiplying it by 17. You want this:

def dec2hex(d):
    """return a two character hexadecimal string representation of integer d"""
    return "%02X" % d

Upvotes: 2

Related Questions