【问题标题】:How to run image classification on multiple images?如何对多张图片进行图片分类?
【发布时间】:2022-12-06 05:43:37
【问题描述】:

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

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

有没有办法在批处理/多个图像上运行它?代码如下:

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

【问题讨论】:

  • 是什么阻止您一起发送多张图片?
  • 将它们堆叠在您创建的批处理线中

标签: python tensorflow


【解决方案1】:

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

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",...]

predictions 是您的模型对给定图像批次做出的预测列表,它们与您用作输入的图像的顺序相同。 所以predictions[x] 为您提供输入批次的第 x 个图像的预测。

【讨论】:

    【解决方案2】:

    这是一个使用 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))
    

    【讨论】:

      猜你喜欢
      • 2016-10-16
      • 2018-03-10
      • 2016-04-16
      • 1970-01-01
      • 1970-01-01
      • 2017-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多