You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将0-1范围的浮点型二维数组转换为灰度图像?

将0-1浮点二维数组转为灰度图像(白1黑0)

你需要把取值范围0-1的浮点型二维正方形数组转为灰度图像,要求值为1时显示白色、0时显示黑色,以下是基于Matplotlib和Pillow的两种简单实现方案:

示例数组

# 第一个5x5数组
arr1 = [
    [0.48, 0.4, 0.56, 0.32, 0.52],
    [0.36, 0.56, 0.56, 0.68, 0.56],
    [0.32, 0.72, 0.88, 0.44, 0.56],
    [0.56, 0.64, 0.76, 0.52, 0.48],
    [0.32, 0.88, 0.56, 0.52, 0.4]
]

# 第二个3x3数组
arr2 = [
    [0.33333333, 0.22222222, 0.33333333],
    [0.22222222, 0.44444444, 0.11111111],
    [0.44444444, 0.11111111, 0.11111111]
]

方案1:使用Matplotlib

Matplotlib的imshow可以直接处理0-1的浮点数组,只需指定灰度配色映射,并固定取值范围即可:

import matplotlib.pyplot as plt
import numpy as np

# 将列表转为numpy数组(Matplotlib对numpy数组支持更好)
arr_np = np.array(arr1)

# 绘制图像,cmap='gray'指定灰度,vmin/vmax固定0黑1白
plt.imshow(arr_np, cmap='gray', vmin=0, vmax=1)
plt.axis('off')  # 隐藏坐标轴

# 保存图像(可选)
plt.savefig('gray_image_matplotlib.png', bbox_inches='tight', pad_inches=0)

# 显示图像
plt.show()

方案2:使用Pillow

Pillow需要将0-1的浮点数转换为0-255的8位整数(对应灰度值),再创建图像:

from PIL import Image
import numpy as np

# 将列表转为numpy数组,乘以255后转为uint8类型(0-255)
arr_np = np.array(arr2) * 255
arr_uint8 = arr_np.astype(np.uint8)

# 创建灰度图像
img = Image.fromarray(arr_uint8, mode='L')  # mode='L'表示8位灰度

# 保存图像(可选)
img.save('gray_image_pillow.png')

# 显示图像
img.show()

注意:两种方案都依赖numpy来处理数组转换,若未安装可通过pip install numpy matplotlib pillow安装所需库。

内容的提问来源于stack exchange,提问作者Curtis Milligan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 20:05:33