使用Python / PIL从图像中删除背景颜色

时间:2014-01-19 13:30:17

标签: python image python-2.7 python-imaging-library

我一直试图让这个工作起来并且我遇到了麻烦,所以非常感谢你的帮助。

使用下面的代码,我想将指定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')

1 个答案:

答案 0 :(得分:7)

沿第三轴使用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')