Python 获取图片主色调

参考地址:https://blog.csdn.net/int93/article/details/78954129
注意:Python3 要先下载pillow第三方模块 pip install pillow

import colorsys
import PIL.Image as Image
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]):
    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

image = Image.open('./1.jpg')
image = image.convert('RGB')
print(get_dominant_color(image))

你可能感兴趣的:(Python 获取图片主色调)