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

如何提取28×28 matplotlib图像的灰度像素值数组?

问题:如何访问MNIST图像的像素灰度值并遍历

我正在编写神经网络,目前处于初期阶段,卡在了一个问题上。我已有可从MNIST数据库提取图像并通过matplotlib显示的代码,现在需要提取每个像素的灰度值(范围0-255),但不知道如何访问和遍历图像上的每个像素。

示例图:手绘数字的Matplotlib显示

我的现有代码如下:

import numpy as np
import gzip
import matplotlib.pyplot as plt
import random
from PIL import Image
f = gzip.open('train-images-idx3-ubyte.gz','r')

image_size = 28
num_images = 10000


f.read(16)
buf = f.read(image_size * image_size * num_images)
data = np.frombuffer(buf, dtype=np.uint8).astype(np.float32)
data = data.reshape(num_images, image_size, image_size, 1)
x = random.randrange(0, 10000)
image = np.asarray(data[x]).squeeze()
plt.style.use('grayscale')
plt.imshow(image)
plt.show()

我曾尝试寻找按(行,列)调用像素值的方法但未找到,有人说在matplotlib上无法实现,但鼠标悬停时能看到像素值,所以肯定有方法,我希望能遍历图像像素。


解决方案

你的image变量本质是一个28×28的NumPy数组,所有像素的灰度值都存在这里,完全不需要依赖Matplotlib来获取。

1. 访问单个像素

NumPy数组采用0起始索引,直接通过[行索引, 列索引]就能读取对应位置的灰度值:

# 获取第3行第5列的像素值(注意索引从0开始,所以行是2,列是4)
pixel_value = image[2, 4]
print(pixel_value)

2. 遍历所有像素

有两种常见方式:

方式一:嵌套循环遍历行和列

适合需要同时获取行/列坐标的场景:

image_size = 28
# 遍历每一行
for row_idx in range(image_size):
    # 遍历当前行的每一列
    for col_idx in range(image_size):
        gray_value = image[row_idx, col_idx]
        # 这里可以添加处理逻辑,比如打印或存储
        print(f"坐标({row_idx}, {col_idx}) 灰度值: {gray_value:.0f}")

方式二:扁平化数组遍历

如果不需要坐标,直接把二维数组转成一维后遍历更简洁:

# 将28×28的图像转为一维数组,包含所有784个像素值
all_pixels = image.flatten()
for idx, gray_value in enumerate(all_pixels):
    # 可选:从一维索引反推行列坐标
    row_idx = idx // image_size
    col_idx = idx % image_size
    print(f"坐标({row_idx}, {col_idx}) 灰度值: {gray_value:.0f}")

补充说明

你看到Matplotlib鼠标悬停显示像素值,是因为它读取了image这个NumPy数组的数据,并非Matplotlib自身存储了像素信息。另外,你代码里把原始uint8类型转成了float32,如果想让灰度值显示为0-255的整数,可以再转回来:

image = image.astype(np.uint8)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 07:35:16