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

如何从ImageDataGenerator生成的Python图像数组中获取RGB值

你当前代码的报错原因是 img[i] 已经是加载完成的numpy图像数组,不是本地图片路径,不能直接传入 Image.open() 读取。你可以直接通过数组索引获取指定位置的RGB值,具体实现如下:

import tensorflow as tf
from keras_preprocessing.image import ImageDataGenerator
import numpy as np
import matplotlib.pyplot as plt

Training_data_dir = "D:\CODES\data"
batch_size = 4

training_data_Augmentation = ImageDataGenerator()

train_generator = training_data_Augmentation.flow_from_directory(
    Training_data_dir,
    batch_size=batch_size,
    target_size=(50, 150),
    class_mode='categorical',
    shuffle=True
)

img_batch, label_batch = next(train_generator)
# 要获取的像素坐标:x=15, y=17
target_x = 15
target_y = 17

for i in range(batch_size):
    # 数组索引顺序为 [图像索引, y坐标, x坐标, 通道索引],通道0=R、1=G、2=B
    r, g, b = img_batch[i, target_y, target_x]
    # 像素值如果是float32类型可以转成int方便查看
    r, g, b = int(r), int(g), int(b)
    print(f'第{i+1}张图,坐标({target_x},{target_y})的RGB值:R:{r} G:{g} B:{b}')

补充注意事项:

  • 如果你的ImageDataGenerator配置了归一化(比如设置了rescale=1/255.),像素值会变成01的浮点数,需要乘以255再转成整数才能得到常规0255范围的RGB值
  • 数组的坐标顺序不要搞反:target_size设置的是(高度, 宽度),对应numpy数组的第1、2维度是[y轴坐标, x轴坐标]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 16:09:04