Displaying a grayscale Image


My aim:

  1. Read an image into the PIL format.
  2. Convert it to grayscale.
  3. Plot the image using pylab.

Here is the code i'm using:

from PIL import Image
from pylab import *
import numpy as np


imageArray= np.asarray(pilImage)





My Problem: The image get's displayed like the colours are inverted.

This is the Original Image

This is how it appears in the Python Window

But I know that the image is getting converted to grayscale, because when I write it to the disk it is appearing as a grayscale image.(Just as I expect).

I feel that the problem is somewhere in the numpy conversion.

I've just started programming in Python for Image Processing. And Tips and Guideline will also be appreciated.

10/25/2014 5:50:58 PM

Accepted Answer

You want to over-ride the default color map:

imshow(imageArray, cmap="Greys_r")

Here's a page on plotting images and pseudocolor in matplotlib .

10/25/2014 5:48:44 PM

This produces a B&W image:

pilImage = pilImage.convert('1')   #this convert to black&white


From the convert method docs:


im.convert(mode) => image

Returns a converted copy of an image.
When translating from a palette image, this translates pixels through the palette.
If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette.

When from a colour image to black and white, the library uses the ITU-R 601-2 luma transform:

    L = R * 299/1000 + G * 587/1000 + B * 114/1000
When converting to a bilevel image (mode "1"), the source image is first converted to black and white.
Resulting values larger than 127 are then set to white, and the image is dithered.
To use other thresholds, use the point method.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow