I am trying to create a custom generator. I saw in this question Custom Keras Data Generator with yield how no while loop is necessary because they use the sequence API. I am not using a sequence API but my code looks very similar to the code mention. Do I need a while loop because I have not called the sequence API. Also I am using yield to return the image.
import os
import numpy
import cv2
class image_gen():
def __init__(self, sdir, batch_size, shuffle):
self.batch_index=0
self.sdir=sdir # directory containing input images
self.batch_size=batch_size #batch size is number of samples in a batch
# tuple (width, height) for target image
self.shuffle=shuffle # set to True to shuffle images, False for no shuffle
# initialize list to hold sequential list of total labels generated
self.image_list=[] # initialize list to hold sequential list of total images filenames generated
self.s_list=os.listdir(self.sdir) # list of images in directory
def get_images(self): # gets a batch of input images, resizes input image to make target images
input_image_batch=[] # initialize list to hold a batch of target images
# initialize list to hold batches of input images
sample_count=len(self.s_list) # determine total number of images available
for i in range(self.batch_index * self.batch_size, (self.batch_index + 1) * self.batch_size ): #iterate for a batch
j=i % sample_count # cycle j value over range of available images
k=j % self.batch_size # cycle k value over batch size
if self.shuffle: # if shuffle select a random integer between 0 and sample_count-1 to pick as the image=label pair
m=np.random.randint(low=0, high=sample_count-1, size=None, dtype=int)
else:
m=j # no shuffle
path_to_img=os.path.join(self.sdir, self.s_list[m]) # define the path to the m th image
input_image=cv2.imread(path_to_img)
#create the target image from the input image
input_image_batch.append(input_image)
input_image_array=numpy.array((input_image_batch))
self.batch_index=self.batch_index + 1
yield (input_image_array)