简体   繁体   中英

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 ..

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM