2014-11-05 134 views
0

我有一個像這樣的嘈雜背景的圖像(炸燬,每個方塊是一個像素)。我正在嘗試對黑色背景進行標準化處理,以便我可以完全替換顏色。Python PIL比較顏色

這是我在想什麼(僞代碼):

for pixel in image: 
    if is_similar(pixel, (0, 0, 0), threshold): 
     pixel = (0, 0, 0) 

什麼樣的功能,可以讓我比較兩種顏色值在一定閾值內匹配嗎?

+1

看看http://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color,使用亮度公式基本上給你的每個像素的值在灰度從而使您只能在一維中將您的像素與閾值進行比較。 – 2014-11-05 19:58:35

+1

查看維基百科的[Color Difference](http://en.wikipedia.org/wiki/Color_difference)文章,瞭解確定兩種顏色相似程度的幾種方法。最簡單的答案是:將每種顏色視爲三維座標,並使用畢達哥拉斯公式找出它們之間的距離。 – Kevin 2014-11-05 20:07:31

回答

2

我結束了從this answer使用感知的亮度公式。它工作完美。

THRESHOLD = 18 

def luminance(pixel): 
    return (0.299 * pixel[0] + 0.587 * pixel[1] + 0.114 * pixel[2]) 


def is_similar(pixel_a, pixel_b, threshold): 
    return abs(luminance(pixel_a) - luminance(pixel_b)) < threshold 


width, height = img.size 
pixels = img.load() 

for x in range(width): 
    for y in range(height): 
     if is_similar(pixels[x, y], (0, 0, 0), THRESHOLD): 
      pixels[x, y] = (0, 0, 0)