Re: Convert to Black and White to an image

Fredrik Lundh <[email protected]>
Newsgroups gmane.comp.python.image
Message-ID <[email protected]>
2011/1/7 Narendra Sisodiya <[email protected]>:
> 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>
_______________________________________________
Image-SIG maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/image-sig
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.