run_inference_for_single_image(image, graph) - Tensorflow,对象检测

run_inference_for_single_image(image, graph) - Tensorflow, object detection

参照object_detection_tutorial.ipynb。我想知道是否可以 运行 目录中的所有图像。

而不是编写一个 for 循环和 运行宁一个 "run_inference_for_single_image(image, graph)"。有没有办法 运行 对目录中所有图像的推断或 运行 对多个图像的推断。 link

  for f in files:
    if f.lower().endswith(('.png', '.jpg', '.jpeg')):
      image_path = files_dir + '/' + f
       .... // Read image etc.
      output_dict = run_inference_for_single_image(image_np, detection_graph)

这将每次创建 tf.session,我认为它的计算量很大。如有错误请指正

如您所知,'run_inference_for_single_image' 方法每次都创建。 如果你想推断多张图片,你应该更改代码,

  • 方法调用

    images = []
    for f in files:
      if f.lower().endswith(('.png', '.jpg', '.jpeg')):
        image_path = files_dir + '/' + f
        image =  .... // Read image etc.
        images.append(image)
        output_dicts = run_inference_for_multiple_images(images, detection_graph)
    
  • run_inference_for_multiple_images

    def run_inference_for_multiple_images(images, grapg):
      with graph.as_default():
        with tf.Session() as sess:
          output_dicts = []
    
          for index, image in enumerate(images):
            ... same as inferencing for single image
    
             output_dicts.append(output_dict)
    
       return output_dicts
    

此代码将执行一次而不会每次都创建 tf.session。

我从 google 找到了这个教程 - creating-object-detection-application-tensorflow. After looking into its github page --> object_detection_app --> app.py 我们只需要 运行 detect_objects(image_path) 每次我们想要检测一个对象时函数。

根据 GPU 的计算能力和图像的大小,可以 运行 推断一批图像。

第 1 步:将所有测试图像堆叠在一个阵列中:

for image_path in glob.glob(PATH_TO_TEST_IMAGES_DIR + '/*.jpg'):
    image_np = io.imread(image_path)  #
    image_array.append(image_np)
image_array = np.array(image_array)

第 2 步:运行 对批次的推断:(较大的批次大小可能会导致内存不足问题)

  BATCH_SIZE = 5
  for i in range(0, image_array.shape[0],BATCH_SIZE):
    output_dict = sess.run(tensor_dict, feed_dict={image_tensor: image_array[i:i+BATCH_SIZE]})


    print("number of images inferenced = ", i+BATCH_SIZE)
    output_dict_array.append(output_dict)

确保 image_tensor 和 image_array 的尺寸匹配。在这个例子中 image_array 是 (?, height, width, 3)

一些提示:

  1. 您可能只想加载图表一次,因为加载需要几秒钟。
  2. 我观察到使用 skimage.io.imread() 或 cv2.imread() 加载图像的速度相当快。这些函数直接将图像加载为 numpy 数组。
  3. 用于保存图像的 skimage 或 opencv 比 matplotlib 更快。