Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.


1 Answers

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.

like image 141
thushv89 Avatar answered Nov 09 '25 10:11

thushv89



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!