hatmatrix
hatmatrix

Reputation: 44872

Convert image to a matrix in python

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

Upvotes: 32

Views: 93223

Answers (6)

FellerRock
FellerRock

Reputation: 9

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.

Upvotes: 1

anon
anon

Reputation: 1258

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

Upvotes: 7

Salvador Dali
Salvador Dali

Reputation: 222511

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)

Upvotes: 14

ptomato
ptomato

Reputation: 57850

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

Upvotes: 32

Nikolaus Gradwohl
Nikolaus Gradwohl

Reputation: 20124

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

Upvotes: 2

Katriel
Katriel

Reputation: 123632

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

Upvotes: 6

Related Questions