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

限于喜欢 提交于 2019-12-25 04:19:47

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/3597610/hex-rgb-hsv-color-space-conversion-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!