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

Question:

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!

Asked By: ace

||

Answers:

The command os.listdir(mydir) returns a list containing the names of the entries in the directory.

  1. before randomly choosing one element in the list, you must ensure that this element is actually an image file myimage
  2. Your problem is here : importantly, you must set the full path : myfilepath = os.path.join(mydir, myimage)

alternatively you can use glob, which allows wildcards, let’s say for jpeg images :

import glob
image_list = glob.glob(os.path.join(mydir, '*.jpg'))
Answered By: elbe

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)
Answered By: Gerry P

Introduce you that dataset is more suitable to convert of pre-processing data nad transform for next processes.

[ Sample ]:

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
DataSet
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
dataset = tf.data.Dataset.from_tensor_slices((tf.constant(tf.cast(list_file, dtype=tf.int64), shape=(33, 1, 32, 32, 4), dtype=tf.int64),tf.constant(list_label, shape=(33, 1, 1), dtype=tf.int64)))
dataset = tf.data.Dataset.range(33)
dataset = dataset.shuffle(10, reshuffle_each_iteration=True)
Answered By: Jirayu Kaewprateep