# coding: utf-8
import sys, os
sys.path.append(os.pardir)  # 为了导入父目录的文件而进行的设定,将父目录加入模块搜索路径
import numpy as np
from dataset.mnist import load_mnist  # 从 dataset.mnist 模块导入加载 MNIST 数据集的函数
from PIL import Image  # 导入 Python Imaging Library,用于图像处理和显示

# 定义一个函数,用于显示图片
def img_show(img):
    # 将 NumPy 数组转换为 PIL 图像对象,并确保数据类型为 uint8(0~255 像素值)
    pil_img = Image.fromarray(np.uint8(img))
    pil_img.show()  # 显示图像

# 加载 MNIST 数据集
# flatten=True: 图像数据展开为一维数组
# normalize=False: 不对像素值进行归一化(像素值保持 0~255)
(x_train, t_train), (x_test, t_test) = load_mnist(flatten=True, normalize=False)

# 获取训练集中第一张图像及其标签
img = x_train[0]       # 图像数据(展开为 784 维的一维数组)
label = t_train[0]     # 图像对应的标签
print("label", label)  # 打印标签,例如输出: label 5

print("img_shape", img.shape)  # 打印图像数据的形状: (784,)

# 将一维数组重新变换为原始的二维图像 (28x28)
img = img.reshape(28, 28)
print("img_shape", img.shape)  # 打印变换后的图像形状: (28, 28)

# 调用函数显示图像
img_show(img)

更多推荐