以下 Python 代码将一个数组(或矩阵)转换为图像,并将其保存到指定路径:

image = Image.fromarray(image)
image.save(new_file_path)

其中,Image.fromarray(image) 函数将一个 NumPy 数组转换为 PIL 图像对象,然后 image.save(new_file_path) 函数将图像保存到指定路径 new_file_path

示例:

import numpy as np
from PIL import Image

# 创建一个 NumPy 数组
array = np.array([[255, 0, 0], [0, 255, 0], [0, 0, 255]])

# 将数组转换为图像
image = Image.fromarray(array)

# 保存图像
image.save('image.png')

该代码将创建一个 3x3 的红色、绿色、蓝色像素的图像,并将图像保存为名为 'image.png' 的文件。

注意:

  • 数组的每个元素应在 0 到 255 之间,代表像素的 RGB 值。
  • new_file_path 应包含图像文件扩展名(例如 .png、.jpg 等)。

相关资源:

Python 图像处理:从数组转换为图像并保存

原文地址: https://www.cveoy.top/t/topic/qhFG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录