如何用Python将图像转换为NumPy数组并保存为CSV文件
让我们看看如何在Python中把一张图片转换为NumPy数组,然后把这个数组保存到CSV文件中?首先,我们将学习如何将图像转换为Numpy ndarray。有很多方法可以将图像转换为ndarray,其中有几种方法。
方法1:使用PIL和NumPy库。
我们将使用PIL.Image.open()和numpy.asarray()。
示例:
# import required libraries
from PIL import Image
import numpy as gfg
# read an image
img = Image.open('geeksforgeeks.jpg')
# convert image object into array
imageToMatrice = gfg.asarray(img)
# printing shape of image
print(imageToMatrice.shape)
输出:
(251, 335, 3)
方法2:使用Matplotlib库。
我们将使用matplotlib.image.imread()方法。
示例:
# import library
from matplotlib.image import imread
# read an image
imageToMatrice = imread('geeksforgeeks.jpg')
# show shape of the image
print(imageToMatrice.shape)
输出:
(251, 335, 3)
现在,imageToMatrice变量包含了从给定图像转换后得到的ndarray。
获得的矩阵的尺寸由图像中存在多少个通道决定。
- 对于一个黑白或灰度图像。只有一个通道存在,因此,矩阵的形状将是(n,n),其中n代表图像的尺寸(像素),矩阵内的值范围为0至255。
- 对于彩色或RGB图像。它将呈现3个通道的张量,因此矩阵的形状是(n, n,3)。每个通道是一个(n, n)矩阵,每个条目分别代表图像内部实际位置的红、绿或蓝的水平。
我们将使用两种方法来做同样的事情,第一种方法使用numpy库,第二种方法使用pandas库。
注意:我们只能在文件中保存一维或二维矩阵,因此,在灰度或黑白图像中不会有问题,因为它是一个二维矩阵,但我们需要确保这对彩色或RGB图像有效,因为它是一个三维矩阵。
方法1:使用NumPy库。
我们将使用numpy.savetxt()和numpy.loadtxt()。
示例:
# import required libraries
import numpy as gfg
import matplotlib.image as img
# read an image
imageMat = 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 grayscale
else:
# remain as it is
imageMat_reshape = imageMat
# saving matrice to .csv file
gfg.savetxt('geek.csv',
imageMat_reshape)
# retrieving matrice from the .csv file
loaded_2D_mat = gfg.loadtxt('geek.csv')
# reshaping it to 3D matrice
loaded_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 not
if((imageMat == loaded_mat).all()):
print("\n\nYes",
"The loaded matrice from CSV file is same as original image matrice")
输出:
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
方法2:使用Pandas库。
我们将使用pandas.Dataframe( )和pandas.Dataframe() .to_csv()方法。
# import required libraries
import numpy as gfg
import matplotlib.image as img
import pandas as pd
# read an image
imageMat = 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 grayscale
else:
# 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 file
loaded_df = pd.read_csv('gfgfile.csv',
sep = ',',
header = None)
# getting matrice values.
loaded_2D_mat = loaded_df.values
# reshaping it to 3D matrice
loaded_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 not
if((imageMat == loaded_mat).all()):
print("\n\nYes",
"The loaded matrice from CSV file is same as original image matrice")
输出:
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