如何将所有非黑色像素转换为某种颜色?
我想把每一个不是黑色的像素都变成白色(或者其他任意颜色)。
我需要用Python来实现这个功能(最好是用PIL库,不过其他库也可以考虑)。
谢谢!
3 个回答
2
使用PIL
c = color_of_choice
out = im.point(lambda i: c if i>0 else i)
3
试试用 Image.blend()
这个方法。假设你的图片叫 im
。
# conversion matrix: any color to white, black to black
mtx = (1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0)
mask = im.convert("L", mtx) # show() it to get the idea
decal = Image.new("RGB", im.size, (0, 0, 255)) # we fill with blue
Image.blend(im, decal, mask).show() # all black turned blue
这个方法在处理大图片时,速度肯定比逐个像素调用函数要快得多。
3
试试这个:
import sys
from PIL import Image
imin = Image.open(sys.argv[1])
imout = Image.new("RGB", imin.size)
imout.putdata(map(
lambda pixel: (0,0,0) if pixel == (0,0,0) else (255,255,255),
imin.getdata()
)
)
imout.save(sys.argv[2])