[Image-SIG] Convert to Black and White to an image
Fredrik Lundh
fredrik at pythonware.com
Fri Jan 7 18:21:23 CET 2011
2011/1/7 Narendra Sisodiya <narendra at narendrasisodiya.com>:
> Can somebody give an easy way to convert a image into black and white using
> a given threshold..
>
> Currently I am doing like this
>
> image=ImageOps.grayscale(image)
> for i in range(0,width):
> for j in range(0,height):
> if image.getpixel((i,j)) <= 200:
> image.putpixel((i,j),0)
The Image class provides a bunch of primitives that can be used for
pixel- and region-wise operations. To threshold, use the "point"
method which maps an image through a lookup table.
First, load the image and convert to grayscale:
>>> from PIL import Image
>>> im = Image.open("Images/lena.ppm")
>>> im = im.convert("L") # make it grayscale
>>> im
<PIL.Image.Image image mode=L size=128x128 at 0x7F436FB88710>
Then, create a 256-entry lookup table and use it with the point method:
>>> lut = [255 if v > 128 else 0 for v in range(256)]
>>> out = im.point(lut)
>>> out
<PIL.Image.Image image mode=L size=128x128 at 0x7F436FB88650>
>>> out.getcolors()
[(6261, 0), (10123, 255)]
By default, point preserves the pixel mode, but you can map and
convert in one step when going from L to 1:
>>> out = im.point(lut, "1")
>>> out
<PIL.Image.Image image mode=1 size=128x128 at 0x7F436FB93690>
</F>
More information about the Image-SIG
mailing list