import colorsys
import PIL.Image as Image
# 函数生成的是RGB
# RGB转16进制 https://www.sioe.cn/yingyong/yanse-rgb-16/
def get_dominant_color(image):
max_score = 0.0001
dominant_color = None
for count,(r,g,b) in image.getcolors(image.size[0]*image.size[1]):
# 转为HSV标准
saturation = colorsys.rgb_to_hsv(r/255.0, g/255.0, b/255.0)[1]
y = min(abs(r*2104+g*4130+b*802+4096+131072)>>13,235)
y = (y-16.0)/(235-16)
#忽略高亮色
if y > 0.9:
continue
score = (saturation+0.1)*count
if score > max_score:
max_score = score
dominant_color = (r,g,b)
return dominant_color
# RGB转16进制函数
def RGB_to_Hex(tmp):
rgb = tmp.split(',')#将RGB格式划分开来
strs = '#'
for i in rgb:
num = int(i)#将str转int
#将R、G、B分别转化为16进制拼接转换并大写
strs += str(hex(num))[-2:].replace('x','0').upper()
return strs
if __name__ == '__main__':
image = Image.open('blue.jpg')
image = image.convert('RGB')
r=get_dominant_color(image)
print(r)
rgb_str=",".join([ str(x) for x in list(r)] )
print(rgb_str)
hexstr=RGB_to_Hex(rgb_str)
print(hexstr)
效果还可以。先记录一下。