我使用Python 2.7嘗試從網頁截圖中獲取5色調色板。Python獲取網頁截圖調色板
迄今爲止我嘗試過的方法不能產生令人滿意的結果。
當網頁有其他可能不佔主導地位,但應具備重要色彩的調色板時,調色板會集中在綠色,灰色和藍色上。
此處包含一個輸出樣本。我在每個圖像縮略圖上方放置了一個5格的表格,每個表格顯示5種顏色之一。
我與註釋掉方法的代碼低於但我一直在使用Pillow
並呼籲colorthief
一個有前途的模塊來概括。
我認爲這些調色板的大部分練習都適用於場景和物體的照片或圖形,這些場景和物體上充滿了顏色。網頁是不同的。他們有大量的空白和黑色文本。
最好的結果雖然遠非令人滿意,但卻是一種將白色像素變爲透明的方法。這允許一些截圖顯示比藍色,灰色,綠色更多的調色板。
我懷疑如果我可以首先從屏幕截圖中刪除所有白色和黑色像素,並且可能從白色和黑色(例如關閉白色,深灰色)中刪除相關%中的所有其他像素,然後我可以從中生成調色板只有一組顏色的像素。
網頁搜索還沒有透露任何具體處理網頁或文檔調色板生成的技術。
我可能不得不重新考慮調色板生成,並直接從HTML獲取。但如果可能的話,想嘗試使圖像方法起作用。
所以問題是如何從排除白色,黑色和僅基於圖像顏色的網頁的屏幕截圖獲取調色板?
import os, os.path
from PIL import Image
import psycopg2
from colorthief import ColorThief
conn_string = \
"host='localhost' \
dbname='databasename' \
user='username' \
password='password'"
conn = psycopg2.connect(conn_string)
cur = conn.cursor()
## dev paths
screenshots_path = 'path/to/screenshots/'
screenshots_dir = os.listdir(screenshots_path)
for screenshot in screenshots_dir:
if screenshot != 'Thumbs.db':
try:
img_orig = Image.open(screenshots_path + screenshot)
## method 1 replace white pixels with transparent
# img = img_orig.convert("RGBA")
# datas = img.getdata()
# newData = []
# for item in datas:
# if item[0] == 255 and item[1] == 255 and item[2] == 255:
# newData.append((255, 255, 255, 0))
# else:
# newData.append(item)
# img.putdata(newData)
## method 2 - pillow
img = img_orig.convert('P', palette=Image.ADAPTIVE, colors=5)
width, height = img.size
height = img.size[1]
quantized = img.quantize(colors=5, kmeans=3)
palette = quantized.getpalette()[:15]
convert_rgb = quantized.convert('RGB')
colors = convert_rgb.getcolors(width*height)
color_str = str(sorted(colors, reverse=True))
color_str = str([x[1] for x in colors])
print screenshot + ' ' + color_str
## method 3 - colorthief
# try:
# img = Image.open(screenshots_path + screenshot)
# color_thief = ColorThief(screenshots_path + screenshot)
## get the dominant color
# dominant_color = color_thief.get_color(quality=1)
# build a color palette
# color_str = color_thief.get_palette(color_count=5)
# print screenshot + ' ' + str(height) + ' ' + str(color_str)
cur.execute("UPDATE screenshots set color_palette = %s, height = %s WHERE filename like %s", (str(color_str), height, '%' + screenshot + '%',))
conn.commit()
except:
continue
cur.close()
conn.close()
這種聯繫是好的,讓我在尋找正確的方向。 opencv非常簡單。發現另一個[博客文章](http://www.pyimagesearch.com/2014/05/26/opencv-python-k-means-color-clustering/),它具有類似於Python實現的功能,並且工作正常。 – curtisp
順便說一句,感興趣的讀者,我原來的解決方案實際上是工作。它產生的結果與Utkarsh&上面的pyimagesearch鏈接顯示的結果類似。因爲我在表格背景顏色中使用了錯誤的內聯樣式HTML引用(我在每個td中顯示一種顏色),所以我得到了藍/綠顏色。我使用'bgcolor =「rgb(232,147,31)」'而不是'style =「background-color:rgb(232,147,31)」'瀏覽器不喜歡'bgcolor'只在css中內聯。但很高興我挖入opencv。 – curtisp