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

15 Sep, 2021
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:
Python3
# import required librariesfrom PIL import Imageimport numpy as gfg # read an imageimg = Image.open('geeksforgeeks.jpg') # convert image object into arrayimageToMatrice = gfg.asarray(img) # printing shape of imageprint(imageToMatrice.shape)
Output:
(251, 335, 3)
Method 2: Using Matplotlib library.
We will use matplotlib.image.imread() method.
Example:
Python3
# import libraryfrom matplotlib.image import imread # read an imageimageToMatrice  = imread('geeksforgeeks.jpg') # show shape of the imageprint(imageToMatrice.shape)
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:
Python3
# import required librariesimport numpy as gfgimport matplotlib.image as img # read an imageimageMat = img.imread('gfg.jpg')print("Image shape:", imageMat.shape) # if image is colored (RGB)if(imageMat.shape[2] == 3):     # reshape it from 3D matrice to 2D matrice  imageMat_reshape = imageMat.reshape(imageMat.shape[0],                                      -1)  print("Reshaping to 2D array:",        imageMat_reshape.shape) # if image is grayscaleelse:  # remain as it is  imageMat_reshape = imageMat     # saving matrice to .csv filegfg.savetxt('geek.csv',            imageMat_reshape) # retrieving matrice from the .csv fileloaded_2D_mat = gfg.loadtxt('geek.csv') # reshaping it to 3D matriceloaded_mat = loaded_2D_mat.reshape(loaded_2D_mat.shape[0],                                   loaded_2D_mat.shape[1] // imageMat.shape[2],                                   imageMat.shape[2]) print("Image shape of loaded Image:",      loaded_mat.shape) # check if both matrice have same shape or notif((imageMat == loaded_mat).all()):     print("\n\nYes",        "The loaded matrice from CSV file is same as original image matrice")
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.
Python3
# import required librariesimport numpy as gfgimport matplotlib.image as imgimport pandas as pd # read an imageimageMat = img.imread('gfg.jpg')print("Image shape:",      imageMat.shape) # if image is colored (RGB)if(imageMat.shape[2] == 3):     # reshape it from 3D matrice to 2D matrice  imageMat_reshape = imageMat.reshape(imageMat.shape[0],                                      -1)  print("Reshaping to 2D array:",        imageMat_reshape.shape) # if image is grayscaleelse:  # remain as it is  imageMat_reshape = imageMat     # converting it to dataframe.mat_df = pd.DataFrame(imageMat_reshape) # exporting dataframe to CSV file.mat_df.to_csv('gfgfile.csv',              header = None,              index = None) # retrieving dataframe from CSV fileloaded_df = pd.read_csv('gfgfile.csv',                        sep = ',',                        header = None)# getting matrice values.loaded_2D_mat = loaded_df.values # reshaping it to 3D matriceloaded_mat = loaded_2D_mat.reshape(loaded_2D_mat.shape[0],                                   loaded_2D_mat.shape[1] // imageMat.shape[2],                                   imageMat.shape[2]) print("Image shape of loaded Image :",      loaded_mat.shape) # check if both matrice have same shape or notif((imageMat == loaded_mat).all()):  print("\n\nYes",        "The loaded matrice from CSV file is same as original image matrice")
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
akshaysingh98088
Python-matplotlib
Python-numpy
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
sum() function in Python