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

如何不使用Keras和TensorFlow内置函数实现批量读取图像与对应标签

图像标签批量读取生成器实现方案

要实现迭代返回批次的效果,将你原代码中的return替换为Python生成器关键字yield即可,函数执行到yield时会返回当前结果并暂停运行,下次迭代时从暂停位置继续执行,正好符合批次迭代的需求。

假设你的数据集采用常规分类目录结构,根目录下每个子文件夹名称为对应类别标签,子文件夹内存放对应类别的图像文件:

数据集根目录/
├─ 类别A/
│  ├─ 1.jpg
│  └─ 2.jpg
└─ 类别B/
   ├─ 1.jpg
   └─ 2.jpg

完整实现代码

import os
from PIL import Image
import numpy as np

def batch_loader(data_root, batch_size=5, preprocess_fn=None):
    # 第一步:遍历全量数据集,收集所有图像路径和对应标签
    all_img_paths = []
    all_labels = []
    for root, _, files in os.walk(data_root):
        # 跳过根目录,仅处理分类子目录
        if root == data_root:
            continue
        current_label = os.path.basename(root)
        for file in files:
            # 过滤非图像文件,可根据实际数据集格式补充后缀
            if file.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp')):
                full_img_path = os.path.join(root, file)
                all_img_paths.append(full_img_path)
                all_labels.append(current_label)
    
    # 第二步:按批次切分,迭代返回
    total_samples = len(all_img_paths)
    for idx in range(0, total_samples, batch_size):
        # 截取当前批次的路径和标签
        batch_path_slice = all_img_paths[idx:idx+batch_size]
        batch_label_slice = all_labels[idx:idx+batch_size]
        # 读取并处理当前批次的所有图像
        batch_imgs = []
        for img_path in batch_path_slice:
            img = Image.open(img_path).convert('RGB')
            # 若传入了预处理函数则执行预处理
            if preprocess_fn:
                img = preprocess_fn(img)
            batch_imgs.append(np.array(img))
        # 返回当前批次,下次迭代从此处继续
        yield batch_imgs, batch_label_slice

使用示例

# 自定义预处理函数,可根据需求实现尺寸调整、归一化等操作
def preprocess(img):
    # 示例:统一缩放为224*224尺寸
    return img.resize((224, 224))

# 初始化生成器
loader = batch_loader(
    data_root="替换为你的数据集根目录路径",
    batch_size=8,
    preprocess_fn=preprocess
)

# 迭代读取所有批次
for batch_imgs, batch_labels in loader:
    # 此处编写批次处理逻辑
    print(f"当前批次图像数:{len(batch_imgs)},标签数:{len(batch_labels)}")

# 如需手动单批次读取,也可使用next方法
# single_batch = next(loader)
# imgs, labels = single_batch

核心特性

  • 不依赖TensorFlow、Keras等深度学习框架,仅使用基础Python库即可运行
  • 支持自定义预处理逻辑,无需修改核心读取代码
  • 自动过滤非图像文件,可根据实际需求调整支持的图像后缀

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 09:54:04