Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 944
hatmatrix Avatar asked Aug 16 '10 12:08

hatmatrix


People also ask

How do you turn a picture into a matrix?

Convert Image To Matrix in PythonImport Image module from PILLOW library of Python as PIL. Import array module from NUMPY library of Python. These two libraries are for Image extraction from the source file and defining the dimensions of the matrix.

How do you read an image in an array in Python?

imread() function is used to load the image and It also reads the given image (PIL image) in the NumPy array format. Then we need to convert the image color from BGR to RGB. imwrite() is used to save the image in the file.


2 Answers

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

like image 61
ptomato Avatar answered Sep 23 '22 07:09

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)

like image 43
Salvador Dali Avatar answered Sep 22 '22 07:09

Salvador Dali