我有一个 Numpy 数组类型的矩阵。我该如何将其作为图像写入磁盘?任何格式都可以(png、jpeg、bmp……)。一个重要的限制是不存在 PIL。
要将 NumPy 数组作为图像写入磁盘而不使用 PIL,您可以使用该imageio
库。imageio
支持各种图像格式,如 PNG、JPEG、BMP 等。
您可以按照以下方式操作:
imageio
如果尚未安装该库,请安装:pip install imageio
import numpy as np
import imageio
# Example NumPy array (a simple grayscale gradient image)
array = np.arange(256*256).reshape((256, 256)) % 256
# Ensure the array is of type uint8
array = array.astype(np.uint8)
# Save the array as an image
imageio.imwrite('output_image.png', array)
array
用自己的 NumPy 数组替换它。uint8
以确保像素值在[0,255]范围内,这对于图像数据来说很常见。imageio.imwrite
用于将 NumPy 数组保存为图像文件(output_image.png
在本例中)。您可以根据需要更改文件名和格式(例如,“output_image.jpeg”、“output_image.bmp”)。如果您的数组表示 RGB 图像或多通道图像,则数组的形状应为 (高度、宽度、通道)。以下是 RGB 图像的示例:
import numpy as np
import imageio
# Example RGB NumPy array (a simple gradient RGB image)
array = np.zeros((256, 256, 3), dtype=np.uint8)
array[..., 0] = np.arange(256) % 256 # Red channel
array[..., 1] = np.arange(256) % 256 # Green channel
array[..., 2] = np.arange(256) % 256 # Blue channel
# Save the array as an RGB image
imageio.imwrite('output_image_rgb.png', array)
在此示例中,array
是一个 3D 数组,最后一个维度代表 RGB 通道。imageio.imwrite
使用相同的函数来保存图像。
通过遵循这些步骤,您可以将 NumPy 数组保存为各种格式的图像,而无需使用 PIL。