在 Python 中将 NumPy 数组保存为图像
在 Python 中,numpy 模块用于处理数组。Python 中有许多可用的模块,这些模块使我们可以读取和存储图像。
可以将图像视为存储在具有相应颜色代码的特定位置的不同像素的数组。因此,我们可能会遇到需要将数组转换并保存为图像的情况。
在本教程中,我们将讨论如何将 numpy 数组另存为图像。
使用 Image.fromarray()
函数将一个 numpy 数组另存为图像
fromarray()
函数用于从导出数组的对象创建图像内存。然后,我们可以通过提供所需的路径和文件名将图像内存保存到我们所需的位置。
例如,
import numpy as np
from PIL import Image
array = np.arange(0, 737280, 1, np.uint8)
array = np.reshape(array, (1024, 720))
im = Image.fromarray(array)
im.save("filename.jpeg")
我们首先创建一个存储 RGB 颜色代码的数组,然后将其导出。我们可以在文件名中指定图像的所需格式。可以是 jpeg
,png
或任何其他常用的图像格式。这对于下面讨论的所有方法都是很常见的。
使用 imageio.imwrite()
函数将一个 numpy 数组另存为图像
较早之前,scipy 模块具有 imsave()
函数,可将 numpy 数组另存为图像。但是,在最近的版本中,它已被弃用,并且开始推荐使用 image.io()
中的 imwrite()
函数来执行此任务,并因其简单性而广受欢迎。
以下代码显示了如何使用此函数。
import imageio
import numpy as np
array = np.arange(0, 737280, 1, np.uint8)
array = np.reshape(array, (1024, 720))
imageio.imwrite("filename.jpeg", array)
使用 matplotlib.pyplot.imsave()
函数将一个 NumPy 数组另存为图像
matplotlib 模块有多种函数可用于处理图像。
imsave()
函数可以将数组另存为图像文件。
例如,
import matplotlib.pyplot as plt
import numpy as np
array = np.arange(0, 737280, 1, np.uint8)
array = np.reshape(array, (1024, 720))
plt.imsave("filename.jpeg", array)
使用 cv2.imwrite()
函数将一个 numpy 数组另存为图像
OpenCV 模块通常用于 Python 中的图像处理。该模块中的 imwrite()
函数可以将一个 numpy 数组导出为图像文件。
例如,
import cv2
import numpy as np
array = np.arange(0, 737280, 1, np.uint8)
array = np.reshape(array, (1024, 720))
cv2.imwrite("filename.jpeg", array)
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串