中文手写数字识别:手写图片转换为指定数据类型

怎样将文件夹中读取的手写图片转换为以下类型

print(x_test.shape, ",", y_test.shape)
(3000, 64, 64, 1) , (3000, 15)

3000为读取图片的数量,64×64×1为图片大小,15为value数,分为15类

ji求!万分感谢🙏🙏


import os
import cv2
import numpy as np

# 定义图像尺寸和通道数
image_width = 64
image_height = 64
image_channels = 1

# 定义类别数
num_classes = 15

# 定义图像文件夹路径和标签
image_folder = "path/to/image/folder"
labels = os.listdir(image_folder)

# 初始化数据数组
num_images = len(labels)
x_data = np.zeros((num_images, image_width, image_height, image_channels), dtype=np.float32)
y_data = np.zeros((num_images, num_classes), dtype=np.int32)

# 读取和处理图像
for i, label in enumerate(labels):
    label_path = os.path.join(image_folder, label)
    images = os.listdir(label_path)
    for image_name in images:
        image_path = os.path.join(label_path, image_name)
        image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)  # 以灰度模式读取图像
        image = cv2.resize(image, (image_width, image_height))  # 调整图像大小
        image = image.reshape(image_width, image_height, image_channels)  # 调整图像形状
        image = image.astype(np.float32) / 255.0  # 归一化图像像素值

        # 将图像和标签存入数据数组
        x_data[i] = image
        y_data[i, labels.index(label)] = 1

# 打印数据数组的形状
print("x_data shape:", x_data.shape)
print("y_data shape:", y_data.shape)

请注意,上述代码假设图像文件夹中的图像已经按类别存储在各自的子文件夹中,并且每个子文件夹的名称即为对应的标签。您需要将image_folder替换为实际的图像文件夹路径。

代码中的cv2.imread函数用于读取图像,cv2.resize函数用于调整图像大小,image.reshape函数用于调整图像形状,image.astype函数用于将图像数据类型转换为浮点型,并将像素值归一化到0到1之间。

最后,图像数据被存储在x_data数组中,标签数据被存储在y_data数组中,并打印它们的形状。

请根据您的实际情况进行适当的调整,并根据需要添加错误处理和数据增强等步骤。