📌  相关文章
📜  如何将图像转换为 NumPy 数组?

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

如何将图像转换为 NumPy 数组?

图像是表示工作模型的更简单方法。在机器学习中, Python使用以下格式的图像数据 高度、宽度、通道格式。即图像被转换成高度、宽度、通道格式的Numpy Array。

需要的模块:

  • 数字货币: 默认情况下,在更高版本的Python (如 3.x 及更高版本)中,NumPy 可用,如果不可用(在较低版本中),可以使用安装
pip install numpy
  • Pillow:这也必须在以后的版本中显式安装。它是首选的图像处理工具。在Python 3 中,Pillow Python库只不过是 PIL 的升级。它可以安装使用
pip install Pillow

使用以下代码可以轻松检查已安装 Pillow 的版本

Python3
import PIL
  
print('Installed Pillow Version:', PIL.__version__)


Python3
from PIL import Image
  
  
# sample.png is the name of the image
# file and assuming that it is uploaded
# in the current directory or we need
# to give the path
image = Image.open('Sample.png')
  
# summarize some details about the image
print(image.format)
print(image.size)
print(image.mode)


Python3
# Import the necessary libraries
from PIL import Image
from numpy import asarray
  
  
# load the image and convert into
# numpy array
img = Image.open('Sample.png')
  
# asarray() class is used to convert
# PIL images into NumPy arrays
numpydata = asarray(img)
  
# 
print(type(numpydata))
  
#  shape
print(numpydata.shape)


Python3
from PIL import Image
import numpy
  
  
img= Image.open("Sample.png")
np_img = numpy.array(img)
  
print(np_img.shape)


Python3
# Import the necessary libraries
from PIL import Image
from numpy import asarray
  
  
# load the image and convert into 
# numpy array
img = Image.open('Sample.png')
numpydata = asarray(img)
  
# data
print(numpydata)


Python3
# Import the necessary libraries
from PIL import Image
from numpy import asarray
  
  
# load the image and convert into 
# numpy array
img = Image.open('Sample.png')
numpydata = asarray(img)
  
print(type(numpydata))
  
#  shape
print(numpydata.shape)
  
# Below is the way of creating Pillow 
# image from our numpyarray
pilImage = Image.fromarray(numpydata)
print(type(pilImage))
  
# Let us check  image details
print(pilImage.mode)
print(pilImage.size)


Python3
from keras.preprocessing.image import load_img
import warnings
  
# load the image via load_img 
# function
img = load_img('sample.png')
  
# details about the image printed below
print(type(img)) 
print(img.format)
print(img.mode)
print(img.size)


Python3
from keras.preprocessing.image import load_img
import warnings
from keras.preprocessing.image import img_to_array
from keras.preprocessing.image import array_to_img
  
  
# load the image via load_img function
img = load_img('sample.png')
  
# details about the image printed below
print(type(img))
print(img.format)
print(img.mode)
print(img.size)
  
# convert the given image into  numpy array
img_numpy_array = img_to_array(img)
print("Image is converted and NumPy array information :")
  
# 
print(type(img_numpy_array))
  
# type: float32
print("type:", img_numpy_array.dtype)
  
# shape: (200, 400, 3)
print("shape:", img_numpy_array.shape)
  
# convert back to image
img_pil_from_numpy_array = array_to_img(img_numpy_array)
  
# 
print("converting NumPy array into image:",
      type(img_pil_from_numpy_array))


Python3
import cv2
  
image = cv2.imread('Sample.png')
  
# BGR -> RGB
img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
  
cv2.imwrite('opncv_sample.png', img) 
print (type(img))


输出:

Installed Pillow Version: 7.2.0

通过枕头库加载图像

让我们检查是否有 PNG 或 JPEG 格式的图像。图像可以通过其路径引用。图像类是 PIL 的核心。它具有打开图像的 open()函数,可以检索数字文件格式以及像素格式。

使用的图像:

Python3

from PIL import Image
  
  
# sample.png is the name of the image
# file and assuming that it is uploaded
# in the current directory or we need
# to give the path
image = Image.open('Sample.png')
  
# summarize some details about the image
print(image.format)
print(image.size)
print(image.mode)

输出 :

PNG
(400, 200)
RGB

图像转换为 NumPy 数组

Python提供了许多模块和 API,用于将图像转换为 NumPy 数组。让我们详细讨论其中的几个。

使用 NumPy 模块

Numpy 模块本身提供了各种方法来做同样的事情。这些方法是——

方法一:使用asarray()函数

asarray()函数用于将 PIL 图像转换为 NumPy 数组。该函数转换 数组的输入

Python3

# Import the necessary libraries
from PIL import Image
from numpy import asarray
  
  
# load the image and convert into
# numpy array
img = Image.open('Sample.png')
  
# asarray() class is used to convert
# PIL images into NumPy arrays
numpydata = asarray(img)
  
# 
print(type(numpydata))
  
#  shape
print(numpydata.shape)

输出 :


(200, 400, 3)

方法二:使用 numpy.array()函数

通过使用将图像作为参数并转换为 NumPy 数组的 numpy.array()函数

Python3

from PIL import Image
import numpy
  
  
img= Image.open("Sample.png")
np_img = numpy.array(img)
  
print(np_img.shape)

输出 :

(200, 400, 3)

为了获取 NumPy 数组图像的每个像素的值,我们需要打印从 asarray()函数或 array()函数获取的检索数据。

Python3

# Import the necessary libraries
from PIL import Image
from numpy import asarray
  
  
# load the image and convert into 
# numpy array
img = Image.open('Sample.png')
numpydata = asarray(img)
  
# data
print(numpydata)

输出 :

[[[111  60   0]
 [116  65   0]
 [122  69   0]
 ...
 [ 97  47   0]
 [ 99  47   0]
 [100  49   0]]
[[111  61   0]
 [118  65   0]
 [122  69   0]
 ...
 [ 97  47   0]
 [ 99  48   0]
 [100  49   0]]
[[118  65   0]
 [122  69   0]
 [126  73   3]
 ...
 [ 98  48   0]
 [100  49   0]
 [100  49   0]]
...
[[ 96  44   7]
 [ 95  43   6]
 [ 93  41   4]
 ...
 [225  80   3]
 [228  80   0]
 [229  78   0]]
[[ 93  40   6]
 [ 90  37   5]
 [ 85  32   0]
 ...
 [226  81   4]
 [231  80   1]
 [232  79   1]]
[[ 89  36   4]
 [ 84  31   0]
 [ 79  26   0]
 ...
 [228  81   4]
 [232  81   4]
 [233  80   2]]]

从转换后的 Numpy 数组中取回图像

Image.fromarray()函数有助于从转换后的 numpy 数组中取回图像。来回转换后,我们得到的像素也是一样的。因此,这是非常有效的

Python3

# Import the necessary libraries
from PIL import Image
from numpy import asarray
  
  
# load the image and convert into 
# numpy array
img = Image.open('Sample.png')
numpydata = asarray(img)
  
print(type(numpydata))
  
#  shape
print(numpydata.shape)
  
# Below is the way of creating Pillow 
# image from our numpyarray
pilImage = Image.fromarray(numpydata)
print(type(pilImage))
  
# Let us check  image details
print(pilImage.mode)
print(pilImage.size)

输出 :


(200, 400, 3)

RGB
(400, 200)

使用 Keras API 转换图像

Keras API 提供了加载、转换和保存图像数据的功能。 Keras 可以在 TensorFlow 框架之上运行,因此这是必须的。深度学习计算机视觉图像需要 Keras API。要安装它,请在终端中键入以下命令

pip install keras

因为 Keras 需要 TensorFlow 2.2 或更高版本。如果不存在,则需要安装它。要安装它,请在终端中键入以下命令。

pip install tensorflow

Python3

from keras.preprocessing.image import load_img
import warnings
  
# load the image via load_img 
# function
img = load_img('sample.png')
  
# details about the image printed below
print(type(img)) 
print(img.format)
print(img.mode)
print(img.size)

输出 :


PNG
RGB
(400, 200)

使用 Keras API,将图像转换为 Numpy 数组并从 Numpy 数组还原图像

Python3

from keras.preprocessing.image import load_img
import warnings
from keras.preprocessing.image import img_to_array
from keras.preprocessing.image import array_to_img
  
  
# load the image via load_img function
img = load_img('sample.png')
  
# details about the image printed below
print(type(img))
print(img.format)
print(img.mode)
print(img.size)
  
# convert the given image into  numpy array
img_numpy_array = img_to_array(img)
print("Image is converted and NumPy array information :")
  
# 
print(type(img_numpy_array))
  
# type: float32
print("type:", img_numpy_array.dtype)
  
# shape: (200, 400, 3)
print("shape:", img_numpy_array.shape)
  
# convert back to image
img_pil_from_numpy_array = array_to_img(img_numpy_array)
  
# 
print("converting NumPy array into image:",
      type(img_pil_from_numpy_array))

输出 :


PNG
RGB
(400, 200)
Image is converted and NumPy array information :

type: float32
shape: (200, 400, 3)
converting NumPy array into image: 

从上面的输出中,我们可以检查源图像 PIL.Image.Image 和目标图像类型是否相同。

使用 OpenCV 库

从 3.x 开始的 OpenCV 版本具有 DNN 和 Caffe 框架,它们对解决深度学习问题非常有帮助。它可以通过使用安装

pip install opencv-contrib-python

cv2包有以下方法

  • imread()函数用于加载图像,它还以 NumPy 数组格式读取给定图像(PIL 图像)。
  • 然后我们需要将图像颜色从 BGR 转换为 RGB。
  • imwrite() 用于将图像保存在文件中。

Python3

import cv2
  
image = cv2.imread('Sample.png')
  
# BGR -> RGB
img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
  
cv2.imwrite('opncv_sample.png', img) 
print (type(img))

输出 :

结论

Python是一个非常灵活的工具,我们已经看到了将图像转换为 Numpy 数组的方法,以及类似地使用不同的 API 转换回图像的方法。操作转换后的数组并形成不同的图像数据,可以输入深度学习神经网络。