![]() |
VOOZH | about |
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:
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