[Python] Python通过PIL获取图片的主要颜色并和颜色库进行对比的代码 →→→→→进入此内容的聊天室

来自 , 2019-05-13, 写在 Python, 查看 113 次.
URL http://www.code666.cn/view/3a01fc08
  1. import colorsys
  2.  
  3. def get_dominant_color(image):
  4.    
  5. #颜色模式转换,以便输出rgb颜色值
  6.     image = image.convert('RGBA')
  7.    
  8. #生成缩略图,减少计算量,减小cpu压力
  9.     image.thumbnail((200, 200))
  10.    
  11.     max_score = None
  12.     dominant_color = None
  13.    
  14.     for count, (r, g, b, a) in image.getcolors(image.size[0] * image.size[1]):
  15.         # 跳过纯黑色
  16.         if a == 0:
  17.             continue
  18.        
  19.         saturation = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0)[1]
  20.        
  21.         y = min(abs(r * 2104 + g * 4130 + b * 802 + 4096 + 131072) >> 13, 235)
  22.        
  23.         y = (y - 16.0) / (235 - 16)
  24.        
  25.         # 忽略高亮色
  26.         if y > 0.9:
  27.             continue
  28.        
  29.         # Calculate the score, preferring highly saturated colors.
  30.         # Add 0.1 to the saturation so we don't completely ignore grayscale
  31.         # colors by multiplying the count by zero, but still give them a low
  32.         # weight.
  33.         score = (saturation + 0.1) * count
  34.        
  35.         if score > max_score:
  36.             max_score = score
  37.             dominant_color = (r, g, b)
  38.    
  39.     return dominant_color
  40.  
  41.  
  42. #//python/8655

回复 "Python通过PIL获取图片的主要颜色并和颜色库进行对比的代码"

这儿你可以回复上面这条便签

captcha