如何在多个图像上运行图像分类



我已经完成了tensorflow网站上的图像分类教程

本教程介绍了如何将经过训练的模型作为预测器在新图像上运行。

有没有办法在一批/多个图像上运行此操作?代码如下:

sunflower_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/592px-Red_sunflower.jpg"
sunflower_path = tf.keras.utils.get_file('Red_sunflower', origin=sunflower_url)
img = tf.keras.utils.load_img(
sunflower_path, target_size=(img_height, img_width)
)
img_array = tf.keras.utils.img_to_array(img)
img_array = tf.expand_dims(img_array, 0) # Create a batch
predictions = model.predict(img_array)
score = tf.nn.softmax(predictions[0])
print(
"This image most likely belongs to {} with a {:.2f} percent confidence."
.format(class_names[np.argmax(score)], 100 * np.max(score))
)

您可以使用此代码同时对多个图像运行预测。

import cv2 (pip install opencv-python)
batch_images = [cv2.imread(img) for img in list_images] 
predictions = model.predict_on_batch(batch_images)

list_images是一个列表,其中包含要预测的图像的路径,例如["path_img1","path_img2",...]

预测是您的模型对给定的一批图像所做的预测的列表,它们与您用作输入的图像的顺序相同。因此CCD_ 2为您提供输入批次的第x个图像的预测。

这里有一个解决方案,它使用Dataset.from_generator通过生成器函数从磁盘流式传输图像。

def read_dir():
files = os.listdir(source_folder)
for file_name in files:
yield keras.utils.load_img(source_folder + file_name, color_mode="rgb")
ds = tf.data.Dataset.from_generator(
lambda: read_dir(),
output_types=(tf.int8),
output_shapes=([128, 128, 3])
)
model = keras.models.load_model('my-model.keras')
predictions = model.predict(ds.batch(64))

最新更新