[英]How can I convert every pixel that is not black to a certain color?
I want every pixel that is not black to be set to white (or any arbitrary color).我希望每个不是黑色的像素都设置为白色(或任何任意颜色)。
I need this in Python (preferably using PIL, but other libraries can also be considered)我在 Python 中需要这个(最好使用 PIL,但也可以考虑其他库)
Thanks谢谢
Try this:尝试这个:
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])
Try using Image.blend()
.尝试使用
Image.blend()
。 Suppose your image is im
.假设您的图像是
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
This must be way faster than per-pixel lambda calls, especially on large images.这必须比每像素 lambda 调用快得多,尤其是在大图像上。
using PIL使用 PIL
c = color_of_choice
out = im.point(lambda i: c if i>0 else i)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.