keras如何批量读取图片_Keras学习笔记一:修改数据读入方式为本地图片读入

这篇博客介绍了如何在Keras中修改数据读入方式,从本地MNIST图片数据集读取并处理图像。通过ImageDataGenerator和文件操作,将图片逐个读入内存,用于训练和测试。此外,还提供了两种不同的方法来实现这一过程,包括使用flow_from_directory和glob模块。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一种方法:

Keras官方给的图片去噪示例要自动下载mnist数据集并处理,不能修改和加入自己的数据集。

from keras.datasets importmnist

(x_train, _), (x_test, _)=mnist.load_data()

x_train= x_train.astype('float32') / 255.

x_test= x_test.astype('float32') / 255.

以上代码实现了把mnist数据集读到x_train 和x_test 中并且丢弃标签,全过程是封闭的

现需要将本地的mnist数据集,解压成图片格式,然后通过文件操作把图片一个一个读进去同样存在x_train 和x_test 中,并且能和原来的程序完美衔接。

修改如下:

mnist数据集放到和py文件同一个目录,名为MNIST_data,将下载的二进制文件转为图片见 https://www.cnblogs.com/dzzy/p/10824072.html

目录树如图

import os

base_dir = 'MNIST_data' #基准目录

train_dir = os.path.join(base_dir,'mnist_train') #train目录#file1 = os.listdir(train_dir) #读目录下的图#image1 = [os.path.join(train_dir,i) for i in file1] #合成每一个图的路径名称

validation_dir="".join(train_dir)

test_datagen= ImageDataGenerator(rescale= 1./255)

validation_generator=test_datagen.flow_from_directory(validation_dir,

target_size= (28,28),

color_mode= "grayscale",

batch_size= 60000,

class_mode= "categorical")#利用test_datagen.flow_from_directory(图像地址,单通道,目标size,批量数目,标签分类情况)

for x_train,batch_labels invalidation_generator:breaktest_dir= os.path.join(base_dir,'mnist_test') #test目录#file2 = os.listdir(test_dir) #读目录下的图#image2 = [os.path.join(test_dir,i) for i in file2] #合成每一个图的路径名称

validation_dir="".join(test_dir)

test_datagen= ImageDataGenerator(rescale= 1./255)

validation_generator=test_datagen.flow_from_directory(validation_dir,

target_size= (28,28),

color_mode= "grayscale",

batch_size= 10000,

class_mode= "categorical")#利用test_datagen.flow_from_directory(图像地址,单通道,目标size,批量数目,标签分类情况)

for x_test,batch_labels invalidation_generator:break

#创造有噪声的图像

noise_factor = 0.5

x_train_noisy = x_train + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_train.shape)

x_test_noisy = x_test + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_test.shape)

x_train_noisy = np.clip(x_train_noisy, 0., 1.)

x_test_noisy = np.clip(x_test_noisy, 0., 1.)

x_train_noisy = x_train_noisy.astype(np.float)

x_test_noisy = x_test_noisy.astype(np.float)

可以达到同样的效果,只是将图片逐个读到内存需要多花一些时间

第二种方法:

import glob

from PIL import Image

Datapath = "MNIST_data/mnist_train/*.png"x_train=np.zeros(x_train.shape)

i=0for imageFile inglob.glob(Datapath ):#打开图像并转化为数字矩阵

img =np.array(Image.open(imageFile))

img= np.reshape(img, (1, 28, 28, 1))

img= img.astype('float32') / 255.

x_train[i]=img

i+= 1

要求图片都在mnist_train目录下,同样可以达到目的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值