Search code examples
pythontensorflowkerasconv-neural-networkgoogle-colaboratory

How to select a random image from a folder for CNN test process?


I would like to ask if there is any way for my codes to select an image randomly from a folder containing a lot of fruit images. The idea is to test my CNN model using a random image. Here is my code that I've tried but there is an error as shown below.

from keras.preprocessing import image
import numpy as np
import os
import random

test_img  = random.choice(os.listdir("drive/My Drive/HAZIQ/TESTTEST/MODELTEST/"))
img = image.load_img(test_img, target_size = (208,256))
img = image.img_to_array(img, dtype=np.uint8)
img = np.array(img)/255.0
prediction = model.predict(img[np.newaxis, ...])

print("Probability: ",np.max(prediction[0], axis=-1))
predicted_class = class_names[np.argmax(prediction[0], axis=-1)]
print("Classified: ",predicted_class,'\n')

plt.axis('off')
plt.imshow(img.squeeze())
plt.title("Loaded Image")

THE ERROR

FileNotFoundError Traceback (most recent call > last) in () > 5 > 6 test_img = random.choice(os.listdir("drive/My Drive/HAZIQ/TESTTEST/MODELTEST/")) > ----> 7 img = image.load_img(test_img, target_size = (208,256)) > 8 img = image.img_to_array(img, dtype=np.uint8) > 9 img = np.array(img)/255.0 1 frames /usr/local/lib/python3.7/dist-packages/keras_preprocessing/image/utils.py > in load_img(path, grayscale, color_mode, target_size, interpolation) > 111 raise ImportError('Could not import PIL.Image. ' > 112 'The use of load_img requires PIL.') > --> 113 with open(path, 'rb') as f: > 114 img = pil_image.open(io.BytesIO(f.read())) > 115 if color_mode == 'grayscale': FileNotFoundError: [Errno 2] No such file or directory: '32660-3194-5469.jpg'

I can confirm that '32660-3194-5469.jpg' is in the folder. I don't know why it says No such file or directory.

I want it to be like this

enter image description here

Any help would be great.

Thanks!


Solution

  • the code

    os.listdir("drive/My Drive/HAZIQ/TESTTEST/MODELTEST/")
    

    will return a file name but NOT the full path to the file and consequently it is not found. What you need to do is

    sdir=r'drive/My Drive/HAZIQ/TESTTEST/MODELTEST/'
    flist=os.listdir(sdir)
    test_img=random.choice(flist)
    test_img=os.path.join(sdir, test_img)