How to Convert an Image into a Numpy Array in Python


In this article, we show how to convert an image into a Numpy array in Python.

When an image is converted into a numpy array, the image is preserved just as it was before, but comes with a grid line measuring the length and the height of the image.

Therefore, converting an image into a numpy array gives, or adds, additional information to the image.

So let's now show how to convert an image into a numpy array.

The image we are going to use in this example is a jpeg image of a tree shown below.

After we convert this image into a numpy array, the following will be displayed shown below.

You can see now how the numpy image has horizontal and vertical numbering.

Below is the code to convert an image into a numpy array.

Now we will go over the code to convert an image into a numpy array.

First, we must import all our modules, which includes the numpy module, the PIL module, and the matplotlib module.

We next create a variable, pic, which stores the image that we want to work with. In this example, it is 'Tree.jpg'. Since the image is located in our current working directory, we simply specify the name of the image. If the image were located in a different directory, then you would have to specify either the full path or relative path based on the current working directory.

When we use the type() function on this pic variable, we see that is an object of the PIL class.

Next, we use the np.asarray() function to convert the image into a numpy array. We save the result into the variable, picarray.

We next use the type() function to get the type of data that this variable is, which it is now a numpy array.

Being that the data is now an numpy array, we can use the shape attribute, to get the height, width, and number of colors used in the image.

We then use matplotlib to show the image.

And this is how you can have an image represented as a numpy array in Python.

Related Resources

How to Randomly Select From or Shuffle a List in Python

HTML Comment Box is loading comments...