gpt4 book ai didi

python - 在 Python 中没有 float 学的 HSV 到 RGB(和返回)

转载 作者:太空宇宙 更新时间:2023-11-03 14:23:29 25 4
gpt4 key购买 nike

有人知道不依赖于任何外部模块的将 HSV 颜色转换为 RGB(反之亦然)的良好 python 算法吗?我正在编写一些动画生成代码并希望支持 HSV 色彩空间,但它在 Raspberry Pi 上运行并且我试图避免任何 float 。

最佳答案

本站here带您完成这些步骤,包括如何使用整数除法。这是那里描述的 RGB 到 HSV 函数的 python 端口

def RGB_2_HSV(RGB):
''' Converts an integer RGB tuple (value range from 0 to 255) to an HSV tuple '''

# Unpack the tuple for readability
R, G, B = RGB

# Compute the H value by finding the maximum of the RGB values
RGB_Max = max(RGB)
RGB_Min = min(RGB)

# Compute the value
V = RGB_Max;
if V == 0:
H = S = 0
return (H,S,V)


# Compute the saturation value
S = 255 * (RGB_Max - RGB_Min) // V

if S == 0:
H = 0
return (H, S, V)

# Compute the Hue
if RGB_Max == R:
H = 0 + 43*(G - B)//(RGB_Max - RGB_Min)
elif RGB_Max == G:
H = 85 + 43*(B - R)//(RGB_Max - RGB_Min)
else: # RGB_MAX == B
H = 171 + 43*(R - G)//(RGB_Max - RGB_Min)

return (H, S, V)

与 colorsys 函数相比,它给出了正确的结果

import colorsys
RGB = (127, 127, 127)

Converted_2_HSV = RGB_2_HSV(RGB)
Verify_RGB_2_HSV = colorsys.rgb_to_hsv(RGB[0], RGB[1], RGB[2])

print Converted_2_HSV
>>> (0, 0, 127)

print Verify_RGB_2_HSV # multiplied by 255 to bring it into the same scale
>>> (0.0, 0.0, 127.5)

你可以检查输出实际上仍然是一个整数

type(Converted_2_HSV[0])
>>> <type 'int'>

现在是反向功能。原出处可查here ,这里是 Python 端口。

def HSV_2_RGB(HSV):
''' Converts an integer HSV tuple (value range from 0 to 255) to an RGB tuple '''

# Unpack the HSV tuple for readability
H, S, V = HSV

# Check if the color is Grayscale
if S == 0:
R = V
G = V
B = V
return (R, G, B)

# Make hue 0-5
region = H // 43;

# Find remainder part, make it from 0-255
remainder = (H - (region * 43)) * 6;

# Calculate temp vars, doing integer multiplication
P = (V * (255 - S)) >> 8;
Q = (V * (255 - ((S * remainder) >> 8))) >> 8;
T = (V * (255 - ((S * (255 - remainder)) >> 8))) >> 8;


# Assign temp vars based on color cone region
if region == 0:
R = V
G = T
B = P

elif region == 1:
R = Q;
G = V;
B = P;

elif region == 2:
R = P;
G = V;
B = T;

elif region == 3:
R = P;
G = Q;
B = V;

elif region == 4:
R = T;
G = P;
B = V;

else:
R = V;
G = P;
B = Q;


return (R, G, B)

并且我们可以像之前一样验证结果

interger_HSV = (127, 127, 127)
Converted_2_RGB = HSV_2_RGB(interger_HSV)
Verify_HSV_2_RGB = colorsys.hsv_to_rgb(0.5, 0.5, 0.5)

print Converted_2_RGB
>>> (63, 127, 124)

print type(Converted_2_RGB[0])
>>> <type 'int'>

print Verify_HSV_2_RGB # multiplied these by 255 so they are on the same scale
>>> (63.75, 127.5, 127.5)

整数运算确实会引入一些错误,但是根据应用程序的不同,这些错误可能没问题。

关于python - 在 Python 中没有 float 学的 HSV 到 RGB(和返回),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24152553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com