Convert image to a matrix in python

Question:

I want to do some image processing using Python.

Is there a simple way to import .png image as a matrix of greyscale/RGB values (possibly using PIL)?

Asked By: hatmatrix

||

Answers:

im.load in PIL returns a matrix-like object.

Answered By: Katriel

you can use PyGame image and use PixelArray to access the pixeldata

Answered By: Nikolaus Gradwohl

scipy.misc.imread() will return a Numpy array, which is handy for lots of things.

Answered By: ptomato

Up till now no one told about matplotlib.image:

import matplotlib.image as img
image = img.imread(file_name)

Now the image would be a 3D numpy array

print image.shape

Would be something like: (317, 504, 3)

Answered By: Salvador Dali

scipy.misc.imread() is deprecated now. We can use imageio.imread instead of that to read it as a Numpy array

Answered By: anon

Definitely try

from matplotlib.image import imread

image  = imread(filename)  

The filename preferably has to be an .jpg image.
And then, try

image.shape

This would return :

  • for a black and white or grayscale image
    An (n,n) matrix where n represents the dimension of the images (pixels) and values inside the matrix range from 0 to 255.
    Typically 0 is taken to be black, and 255 is taken to be white. 128 tends to be grey!

  • For color or RGB image
    It will render a tensor of 3 channels. Each channel is an (n,n) matrix where each entry represents the respectively the level of Red, Green or Blue at the actual location inside the image.

Answered By: FellerRock