模仿 ImageDataGenerator().flow_from_directory() 实现的图片数据集导入,但返回的是数据与标签

import os
import numpy as np
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.preprocessing.image import img_to_array, load_img


# 多类独热码
def load_dataset_CNN(base_dir, target_size, color_mode='rgb', shuffle=True):
    X, y = [], []
    total_num = 0

    classes = os.listdir(base_dir)
    for clas in classes:
        label = classes.index(clas)
        imgs_dir = os.path.join(base_dir, clas)
        imgs_names = os.listdir(imgs_dir)

        for img_name in imgs_names:
            img_path = os.path.join(imgs_dir, img_name)
            img_PIL = load_img(path=img_path, target_size=target_size, color_mode=color_mode)
            img_array = img_to_array(img_PIL)
            X.append(img_array)
            y.append(label)

        print("Found {} images in class '{}', setting as class[{}].".format(len(imgs_names), clas, label))
        total_num += len(imgs_names)
    print('{} images in total.'.format(total_num))

    X = np.array(X)
    y = to_categorical(np.array(y))

    if shuffle is True:
        state = np.random.get_state()
        np.random.shuffle(X)
        np.random.set_state(state)
        np.random.shuffle(y)

    return X, y

🌰:
在这里插入图片描述

from load_dataset import load_dataset_CNN

IMG_HEIGHT, IMG_WIDTH = 100, 100
X, y = load_dataset_CNN(base_dir='./train', target_size=(IMG_HEIGHT, IMG_WIDTH))
print(X)
print(y)

在这里插入图片描述在这里插入图片描述
👍

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

什鲤子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值