本文實例講述了Python通過PIL獲取圖片主要顏色并和顏色庫進行對比的方法。分享給大家供大家參考。具體分析如下:
這段代碼主要用來從圖片提取其主要顏色,類似Goolge和Baidu的圖片搜索時可以指定按照顏色搜索,所以我們先需要將每張圖片的主要顏色提取出來,然后將顏色劃分到與其最接近的顏色段上,然后就可以按照顏色搜索了。
在使用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 Imageprint get_dominant_color(Image.open('logo.jpg'))
新聞熱點
疑難解答