An alternate to keras’s inbuilt load function incase you want to use your own images.
def load_images(x, paths, limits):
cat1_images = os.listdir(paths[0])[:limits[0]]
cat2_images = os.listdir(paths[1])[:limits[1]]
cat3_images = os.listdir(paths[2])[:limits[2]]
# ...
cat10_images = os.listdir(paths[9])[:limits[9]]
#load images for category 1
for i in range(limits[0]):
#load image
img = load_img(paths[0] + bio_images[i], target_size = (img_height,img_width), color_mode = "grayscale")
#convert to numpy array
training_img_array = img_to_array(img, dtype="float32")
x.append(training_img_array)
#load images for category 2
for i in range(limits[1]):
#load image
img = load_img(paths[1] + fibre_images[i], target_size = (img_height,img_width), color_mode = "grayscale")
#convert to numpy array
training_img_array = img_to_array(img, dtype="float32")
x.append(training_img_array)
# .....
#load images for category 10
for i in range(limits[9]):
#load image
img = load_img(paths[9] + tips_images[i], target_size = (img_height,img_width), color_mode = "grayscale")
#convert to numpy array
training_img_array = img_to_array(img, dtype="float32")
x.append(training_img_array)
#Create training dataset and labels
x_train = []
y_train = []
load_images(x_train, training_paths, train_limits)
print("Number of training images used: " + str(len(x_train)))
create_labels(y_train, categories, train_limits)
print("Number of training labels created: " + str(len(y_train)))
#convert x_train from list to nparray of float32
x_train = np.asarray(x_train)
x_train/=255
print("Shape of training data: " + str(x_train.shape) + "Datatype: " + str(x_train.dtype))
#Converting the labels to arrays
y_train = np.asarray(y_train, dtype="uint8")
# convert class vectors to binary class matrices
Y_train = np_utils.to_categorical(y_train, classes)
print("Training labels shape: " + str(Y_train.shape) + "Datatype: " + str(Y_train.dtype))
- ‘x’ is an empty list that will later contain your training image arrays
- ‘paths’ is a list of folder directories of your images
- ‘limits’ is a list of the number of images in each folder you want to import
Finally x_train and Y_train are the training images and labels in the same format as the output of keras’s load function, which you unfortunately cannot use for your own image datasets.