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

如何在Python中将本地图像数据输入Keras网络?

Hey there! Since you already know your way around MNIST with TensorFlow/Keras, moving to local images is just a matter of using the right tools—let’s break down the two most common approaches that’ll get you up and running quickly.

方法1:用ImageDataGenerator + flow_from_directory(推荐给结构化数据集)

This is the easiest route if your local images are organized into class-specific folders (which is super common for classification tasks). Here's how it works:

第一步:整理你的文件夹结构

First, arrange your images like this (replace class_x with your actual category names):

local_images/
    cats/
        cat_01.jpg
        cat_02.png
        ...
    dogs/
        dog_01.jpg
        dog_02.png
        ...

第二步:编写代码加载并训练

from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Flatten

# 1. 初始化图像生成器(可选添加数据增强)
datagen = ImageDataGenerator(
    rescale=1./255,  # 把像素值归一化到0-1之间
    validation_split=0.2  # 划分20%数据作为验证集
)

# 2. 加载训练集和验证集
train_generator = datagen.flow_from_directory(
    'local_images/',  # 根文件夹路径
    target_size=(28, 28),  # 调整图像尺寸到你的网络输入大小(比如MNIST的28x28)
    batch_size=32,
    class_mode='categorical',  # 多分类用这个,二分类可以用'binary'
    subset='training'
)

val_generator = datagen.flow_from_directory(
    'local_images/',
    target_size=(28, 28),
    batch_size=32,
    class_mode='categorical',
    subset='validation'
)

# 3. 定义并训练模型(这里用个简单的CNN示例)
model = Sequential([
    Conv2D(32, (3,3), activation='relu', input_shape=(28,28,3)),
    MaxPooling2D((2,2)),
    Flatten(),
    Dense(64, activation='relu'),
    Dense(2, activation='softmax')  # 对应你的类别数量
])

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(train_generator, validation_data=val_generator, epochs=10)

Key notes:

  • rescale=1./255 is non-negotiable here—Keras expects pixel values in the 0-1 range for most models.
  • target_size must match the input shape of your model. If your images are RGB, the input shape will have 3 channels (like (28,28,3)); for grayscale, use (28,28,1) and add color_mode='grayscale' to flow_from_directory.

方法2:手动加载图像(适合自定义场景)

If your images aren't neatly organized into class folders, or you need full control over preprocessing, you can load them manually using libraries like PIL or OpenCV:

import os
import numpy as np
from PIL import Image
from sklearn.model_selection import train_test_split
from tensorflow.keras.utils import to_categorical

# 1. 定义参数和空列表
image_dir = 'your_image_folder/'
target_size = (28, 28)
images = []
labels = []

# 2. 遍历文件夹加载图像
# 假设你有一个字典映射文件名到标签,或者按文件名规则提取标签
label_map = {'cat': 0, 'dog': 1}

for filename in os.listdir(image_dir):
    # 跳过非图像文件
    if not filename.endswith(('.jpg', '.png', '.jpeg')):
        continue
    # 提取标签(这里假设文件名是"cat_01.jpg"这种格式)
    label = filename.split('_')[0]
    # 加载并调整图像尺寸
    img = Image.open(os.path.join(image_dir, filename)).resize(target_size)
    # 转成numpy数组并归一化
    img_array = np.array(img) / 255.0
    # 添加到列表
    images.append(img_array)
    labels.append(label_map[label])

# 3. 转换为numpy数组并处理标签
X = np.array(images)
y = to_categorical(np.array(labels))  # 多分类用这个,二分类可以直接用np.array(labels)

# 4. 划分训练测试集
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)

# 5. 训练模型(和之前一样)
model.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=10, batch_size=32)

额外小贴士

  • Always check the shape of your image arrays after loading—make sure they match your model's input shape (e.g., (28,28,3) for RGB, (28,28,1) for grayscale).
  • For grayscale images, use img = Image.open(...).convert('L').resize(target_size) to convert them to single-channel format.
  • If you're dealing with large datasets, the manual approach might use too much memory—stick with flow_from_directory in that case, since it loads images in batches.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:10:39