2014-01-19 345 views
3

我一直試圖讓這個工作,真的有麻煩,所以將非常感謝一些幫助。使用Python/PIL從圖像中刪除背景顏色

使用下面的代碼,我想改變指定的RGB值爲白色的特徵,並將圖像中的所有其他特徵改爲黑色(即基本上從圖像中提取特徵)。不幸的是,儘管我可以使特徵我想「提取」很好,當我嘗試去除背景顏色(我一直在嘗試使用

mask2 = ((red != r1) & (green != g1) & (blue != b1)) 
data[:,:,:4][mask2] = [rb, gb, bb, ab] 

,但似乎選擇除了那些紅色== R1或綠色== G1任何像素等等,給我留下一個很嘈雜的背景圖像。)有沒有人知道用指定的RGB值從字面上提取這些像素的方法,還是更好地重新調整背景像素的方法?

由於

import numpy as np 
from PIL import Image 

im = Image.open('/home/me/nh09sw.tif') 
im = im.convert('RGBA') 
data = np.array(im) 

r1, g1, b1 = 246, 213, 139 # Original value 
rw, gw, bw, aw = 255, 255, 255, 255 # Value that we want to replace features with 
rb, gb, bb, ab = 0, 0, 0, 255 #value we want to use as background colour 

red, green, blue, alpha = data[:,:,0], data[:,:,1], data[:,:,2], data[:,:,3] 

mask = ((red == r1) & (green == g1) & (blue == b1)) 
data[:,:,:4][mask] = [rw, gw, bw, aw] 

im = Image.fromarray(data) 

im.save('/home/me/nh09sw_recol.tif') 

回答

5

使用np.all()沿所述第三軸線相比較。

import numpy as np 
from PIL import Image 

im = Image.open('my_file.tif') 
im = im.convert('RGBA') 
data = np.array(im) 
# just use the rgb values for comparison 
rgb = data[:,:,:3] 
color = [246, 213, 139] # Original value 
black = [0,0,0, 255] 
white = [255,255,255,255] 
mask = np.all(rgb == color, axis = -1) 
# change all pixels that match color to white 
data[mask] = white 

# change all pixels that don't match color to black 
##data[np.logical_not(mask)] = black 
new_im = Image.fromarray(data) 
new_im.save('new_file.tif')