在使用google或者baidu搜圖的時候會發現有一個圖片顏色選項,感覺非常有意思,有人可能會想這肯定是人為的去劃分的,呵呵,有這種可能,但是估計人會累死, 開個玩笑,當然是通過機器識別的,海量的圖片只有機器識別才能做到。
那用python能不能實現這種功能呢?答案是:能
利用python的PIL模塊的強大的圖像處理功能就可以做到,下面上代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
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 |
如何使用:
1
2
3
|
from PIL import Image print get_dominant_color(Image. open ( 'logo.jpg' )) |
這樣就會返回一個rgb顏色,但是這個值是很精確的范圍,那我們如何實現百度圖片那樣的色域呢??
其實方法很簡單,r/g/b都是0-255的值,我們只要把這三個值分別劃分相等的區間,然后組合,取近似值。例如:劃分為0-127,和128-255,然后自由組 合,可以出現八種組合,然后從中挑出比較有代表性的顏色即可。
當然我只是舉一個例子,你也可以劃分的更細,那樣顯示的顏色就會更準確~~大家趕快試試吧
PS:通過pil生成縮略圖的簡單代碼
如果是單純地生成縮略圖,我們可以通過pil很簡單地辦到,這段代碼會強行將圖片大小修改成250x156:
1
2
3
4
|
from PIL import Image img = Image. open ( 'sharejs.jpg' ) img = img.resize(( 250 , 156 ), Image.ANTIALIAS) img.save( 'sharejs_small.jpg' ) |