如何 select CNN 测试过程中的文件夹中的随机图像?

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

请问有没有办法让我的代码从一个包含很多水果图片的文件夹中随机select一张图片。我的想法是使用随机图像测试我的 CNN 模型。这是我试过的代码,但出现如下所示的错误。

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")

错误

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'

我可以确认“32660-3194-5469.jpg”在文件夹中。我不知道为什么它说没有这样的文件或目录。

我想要这样

enter image description here

任何帮助都会很棒。

谢谢!

命令 os.listdir(mydir) returns 包含目录中 条目 名称的列表。

  1. 在随机选择列表中的一个元素之前,您必须确保这个元素实际上是一个图像文件myimage
  2. 你的问题在这里:重要的是,你必须设置完整路径:myfilepath = os.path.join(mydir, myimage)

或者您可以使用 glob,它允许通配符,假设是 jpeg 图像:

import glob
image_list = glob.glob(os.path.join(mydir, '*.jpg'))

代码

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

将 return 文件名但不是文件的完整路径,因此找不到文件。你需要做的是

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)

向您介绍,数据集更适合pre-processing数据的转换和后续流程的转换。

[样本]:

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
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)

[输出]: