python实现grb和hsv转换
发布网友
发布时间:2022-04-25 14:20
我来回答
共2个回答
热心网友
时间:2023-10-08 21:53
这个输出整数还是小数,估计输出整数就可以,如果希望输出浮点数,可以将round去掉。
import math
def hsv2rgb(h, s, v):
h = float(h)
s = float(s)
v = float(v)
h60 = h / 60.0
h60f = math.floor(h60)
hi = int(h60f) % 6
f = h60 - h60f
p = v * (1 - s)
q = v * (1 - f * s)
t = v * (1 - (1 - f) * s)
r, g, b = 0, 0, 0
if hi == 0: r, g, b = v, t, p
elif hi == 1: r, g, b = q, v, p
elif hi == 2: r, g, b = p, v, t
elif hi == 3: r, g, b = p, q, v
elif hi == 4: r, g, b = t, p, v
elif hi == 5: r, g, b = v, p, q
r, g, b = int(r * 255), int(g * 255), int(b * 255)
return r, g, b
def rgb2hsv(r, g, b):
r, g, b = r/255.0, g/255.0, b/255.0
mx = max(r, g, b)
mn = min(r, g, b)
df = mx-mn
if mx == mn:
h = 0
elif mx == r:
h = (60 * ((g-b)/df) + 360) % 360
elif mx == g:
h = (60 * ((b-r)/df) + 120) % 360
elif mx == b:
h = (60 * ((r-g)/df) + 240) % 360
if mx == 0:
s = 0
else:
s = df/mx
v = mx
return h, s, v
if __name__=="__main__":
fp=open("1.txt","w")
for line in open("rgb2hsv.txt",'r'):
r,g,b = map(int,line.split(','))
h,s,v = rgb2hsv(r,g,b)
fp.write("%d,%d,%d\n"%(round(h),round(s),round(v)))
fp.close()
热心网友
时间:2023-10-08 21:53
具体问题是???