📜  如何使用Python将图像转换为 NumPy 数组并保存为 CSV 文件?

📅  最后修改于: 2022-05-13 01:54:31.198000             🧑  作者: Mango

如何使用Python将图像转换为 NumPy 数组并保存为 CSV 文件?

让我们看看如何将图像转换为 NumPy 数组,然后将该数组保存到Python中的 CSV 文件中?首先,我们将学习如何将图像转换为 numpy ndarray。将图像转换为 ndarray 的方法有很多,其中很少有:

方法一:使用PILNumPy库。

我们将使用 PIL.Image.open() 和 numpy.asarray()。

例子:

Python3
# 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)


Python3
# import library
from matplotlib.image import imread
 
# read an image
imageToMatrice  = imread('geeksforgeeks.jpg')
 
# show shape of the image
print(imageToMatrice.shape)


Python3
# 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")


Python3
# 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")


输出:

(251, 335, 3)

方法二:使用Matplotlib库。

我们将使用 matplotlib.image.imread() 方法。

例子:

Python3

# 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 库:

注意:我们只能将 1D 或 2D 矩阵保存在文件中,因此,灰度或黑白图像不会有问题,因为它是 2D 矩阵,但我们需要确保这适用于彩色或RGB 图像,它是一个 3D 矩阵。

方法一:使用NumPy库。

我们将使用 numpy.savetxt() 和 numpy.loadtxt()。

例子:

Python3

# 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")

输出:

方法二:使用Pandas库。

我们将使用 pandas.Dataframe() 和 pandas.Dataframe() .to_csv() 方法。

Python3

# 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")

输出: