对于我的一个应用程序,我需要将颜色从RGB转换为HLS颜色系统,反之亦然。我发现Python的标准库中有花色模块。
问题是,转换有时有点不精确,返回的结果与这个在线颜色转换器略有不同。
下面是我为方便起见编写的前两个小函数的示例:
from __future__ import division
import colorsys
def convert_rgb_to_hls(r, g, b):
h, l, s = colorsys.rgb_to_hls(r/255, g/255, b/255)
return "HLS(" + str(int(round(h * 359))) + ", " + str(int(round(l * 100))) + ", " + str(int(round(s * 100))) + ")"
def convert_hls_to_rgb(h, l, s):
r, g, b = colorsys.hls_to_rgb(h/359, l/100, s/100)
return "RGB(" + str(int(round(r * 255))) + ", " + str(int(round(g * 255))) + ", " + str(int(round(b * 255))) + ")"
根据在线颜色转换器,RGB(123,243,61)应该等于HLS(100,60,88)。使用colorsys函数得到的结果是不同的:
>>> convert_rgb_to_hls(123, 243, 61)
'HLS(99, 59, 88)' # should be HLS(100, 60, 88)
>>> convert_hls_to_rgb(100, 60, 88)
'RGB(122, 243, 63)' # should be RGB(123, 243, 61)
我的第一印象是,这只是一个四舍五入的问题,但从61和63之间的差异来看,似乎还有另一个原因。但这是什么?是否有可能保证颜色系统之间的绝对精确转换?
发布于 2014-05-05 05:45:08
from __future__ import division
import colorsys
def convert_rgb_to_hls(r, g, b):
h, l, s = colorsys.rgb_to_hls(r/255, g/255, b/255)
return "HLS(" + str(int(round(h * 360))) + ", " + str(int(round(l * 100))) + ", " + str(int(round(s * 100))) + ")"
def convert_hls_to_rgb(h, l, s):
r, g, b = colorsys.hls_to_rgb(h/360, l/100, s/100)
return "RGB(" + str(int(round(r * 255))) + ", " + str(int(round(g * 255))) + ", " + str(int(round(b * 255))) + ")"
改变
convert_rgb_to_hls(r, g, b)
上缺少两条圆线。测试
>>> convert_rgb_to_hls(123, 243, 61)
'HLS(100, 60, 88)'
>>> convert_hls_to_rgb(100, 60, 88)
'RGB(123, 243, 63)'
当你说有舍入的错误时,你是对的,但是61和63之间的区别在于当舍入时你失去了精确性。不要为了更好的精度而旋转:
>>> (r_orig, g_orig, b_orig) = (123, 243, 61)
>>> h,l,s = colorsys.rgb_to_hls(r_orig/255, g_orig/255, b_orig/255)
>>> r, g, b = colorsys.hls_to_rgb(h, l, s)
>>> r*255, g*255, b*255
(123.00000000000003, 242.99999999999997, 61.000000000000036)
https://stackoverflow.com/questions/23472290
复制