得到一張圖片或logo的主要顏色(顏色趨向)python版

ybw8 9年前發布 | 19K 次閱讀 Python開發 Python

在使用google或者baidu搜圖的時候會發現有一個圖片顏色選項,感覺非常有意思,有人可能會想這肯定是人為的去劃分的,呵呵,有這種可能,但是估計人會累死,開個玩笑,當然是通過機器識別的,海量的圖片只有機器識別才能做到。

那用python能不能實現這種功能呢?答案是:能

利用python的PIL模塊的強大的圖像處理功能就可以做到,下面上代碼:

import
colorsys
 
def get_dominant_color ( image ):
    
#顏色模式轉換,以便輸出rgb顏色值
     image = image . convert ( 'RGBA' )
    
#生成縮略圖,減少計算量,減小cpu壓力
     image . thumbnail (( 200 , 200 ))
    
     max_score = None
     dominant_color = None
    
     for count , ( r , g , b , a ) in image . getcolors ( image . size [ 0 ] * image . size [ 1 ]):
         # 跳過純黑色
         if a == 0 :
             continue
        
         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
        
         # Calculate the score, preferring highly saturated colors.
         # Add 0.1 to the saturation so we don't completely ignore grayscale
         # colors by multiplying the count by zero, but still give them a low
         # weight.
         score = ( saturation + 0.1 ) * count
        
         if score > max_score :
             max_score = score
             dominant_color = ( r , g , b )
    
     return dominant_color

如何使用:


from PIL import Image
 
print  get_dominant_color(Image.open('logo.jpg'))

這樣就會返回一個rgb顏色,但是這個值是很精確的范圍,那我們如何實現百度圖片那樣的色域呢??
其實方法很簡單,r/g/b都是0-255的值,我們只要把這三個值分別劃分相等的區間,然后組合,取近似值。例如:劃分為0-127,和128-255,然后自由組合,可以出現八種組合,然后從中挑出比較有代表性的顏色即可。
當然我只是舉一個例子,你也可以劃分的更細,那樣顯示的顏色就會更準確~~大家趕快試試吧
 本文由用戶 ybw8 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!