Search code examples
pythonimagekerasartificial-intelligenceclassification

Convert Image to numpy Array (image classification)


I'm following this tutorial: How do I load train and test data from the local drive for a deep learning Keras model? and it went like this name 'train_data' is not defined I know I haven't defined train_data yet, but I don't know what to write inside train_data = ...

My code is look like this

train_path = '/Users/nayageovani/Documents/Artificial Intelligence/dataset/train'
train_batch = os.listdir(train_path)
x_train = []

# if data are in form of images
for sample in train_data:
    img_path = train_path+sample
    x = image.load_img(img_path)
    # preprocessing if required
    x_train.append(x)
test_path = PATH+'/data/test/'
test_batch = os.listdir(test_path)
x_test = []

heres my folder of dataset looks like

|--dataset
  |--test
     |--fresh
     |--rotten
  |--train
     |--fresh
     |--rotten

Solution

  • train_data (and test_data ) should be iterables that contain the file names of your training or test data, respectively.

    You could, for example, create a list of files in the training data directory like:

    import os
    ...
    
    imgTypes = ['jpg', 'png', 'gif', 'bmp']
    train_data = [item for item in os.listdir(train_path) if \
            (os.path.isfile(os.path.join(train_path, item)) and
                os.path.splitext(item)[1].lower() in imgTypes)]
    

    Update:

    A better alternative for loading the image data is using keras' ImageDataGenerator class. Among other things, it directly allows you to preprocess your data while loading.