VOOZH about

URL: https://www.geeksforgeeks.org/python/how-to-convert-an-image-to-numpy-array-and-saveit-to-csv-file-using-python/

⇱ How to Convert an image to NumPy array and saveit to CSV file using Python? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Convert an image to NumPy array and saveit to CSV file using Python?

Last Updated : 15 Jul, 2025

Let's see how to Convert an image to NumPy array and then save that array into CSV file in Python? First, we will learn about how to convert an image to a numpy ndarray. There are many methods to convert an image to ndarray, few of them are:

Method 1: Using PIL and NumPy library.

We will use PIL.Image.open() and numpy.asarray().

Example:

Output:

(251, 335, 3)

Method 2: Using Matplotlib library.

We will use matplotlib.image.imread() method.

Example:

Output:

(251, 335, 3)

Now, imageToMatrice variable contains the ndarray which is obtained after the conversion from the given image. 

The dimension of the matrice obtained is decided by how many channels are present in the image:

  • For a black and white or gray scale image: There is only one channel present, thus, the shape of the matrices would be (n, n) where n represents the dimension of the images (pixels), and values inside the matrix range from 0 to 255.
  • For color or RGB image: It will render a tensor of 3 channels, thus the shape of the matrices would be (n, n,3). Each channel is an (n, n) matrix where each entry represents respectively the level of Red, Green, or Blue at the actual location inside the image.

We will use two methods to do the same, first method using numpy library and the second method using pandas library:

Note: we can save only 1D or 2D matrix in a file, therefore, there would be no issue in the gray scale or black and white image as it is a 2D matrix, but we need to make sure that this works for a colored or RGB image, which is a 3D matrix.

Method 1: Using NumPy library.

We will use numpy.savetxt() and numpy.loadtxt().

Example:

Output:

Image shape: (251, 335, 3) 
Reshaping to 2D array: (251, 1005) 
Image shape of loaded Image: (251, 335, 3)
Yes The loaded matrice from CSV file is same as original image matrice

Method 2: Using Pandas library.

We will use pandas.Dataframe() and pandas.Dataframe() .to_csv() method.

Output:

Image shape: (251, 335, 3) 
Reshaping to 2D array: (251, 1005) 
Image shape of loaded Image : (251, 335, 3)
Yes The loaded matrice from CSV file is same as original image matrice

Comment