user9305579
user9305579

Reputation:

Keras custom data generator from numpy array

I have two numpy variable that contains image and label data respectively. There is 500 labeled image, shape of every image is 240 x 240.

import numpy as np
images = np.random.randint(4, size=(500,240,240))
labels =  np.random.rand(500,240,240)

How can I manke a Keras generator for model training? Thanks in advance for your help.

Upvotes: 4

Views: 2209

Answers (1)

thushv89
thushv89

Reputation: 11333

You can do this easily if you're willing to do a small change to your images. Basically you need to add one more dimension to images (channel dimension).

import numpy as np
import tensorflow as tf

images = np.expand_dims(np.random.randint(4, size=(500,240,240)),-1)
labels =  np.random.rand(500,240,240)

gen = tf.keras.preprocessing.image.ImageDataGenerator()
res = gen.flow(images, labels)
x, y = next(res)

You can post process and remove this dimension by creating another generator that yields the data of the Keras generator and remove that dimension.

Upvotes: 3

Related Questions