[Image-SIG] Convert to Black and White to an image

Narendra Sisodiya narendra at narendrasisodiya.com
Fri Jan 7 19:00:50 CET 2011


On Fri, Jan 7, 2011 at 10:51 PM, Fredrik Lundh <fredrik at pythonware.com>wrote:

> 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>
>


Thanks a lot, This is what i wanted to have. I was expecting some predefined
method. In Octave I was using image to balckNwhite conversion method which
was having threshold as parameter.

Thanks, I will use it., I was not aware of point translation method.




-- 
┌─────────────────────────┐
│    Narendra Sisodiya
│    http://narendrasisodiya.com
└─────────────────────────┘
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/image-sig/attachments/20110107/46077175/attachment.html>


More information about the Image-SIG mailing list