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)
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()
. Suppose your image is 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.
using PIL
c = color_of_choice
out = im.point(lambda i: c if i>0 else i)
精彩评论