【问题标题】:run_inference_for_single_image(image, graph) - Tensorflow, object detectionrun_inference_for_single_image(image, graph) - Tensorflow,物体检测
【发布时间】:2018-09-19 21:21:00
【问题描述】:

参考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,我认为它的计算成本很高。如果我错了,请纠正我。

【问题讨论】:

    标签: tensorflow object-detection


    【解决方案1】:

    如您所知,'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 的情况下每次执行一次。

    【讨论】:

    • 如果我们要一次评估 10 张图像的批次,批量图像评估是否快 10 倍?
    • 就我而言,它并不是快 10 倍。第一张或有时第二张图片与单个版本的经过时间几乎相同。但遗体肯定更快。实际上,当我用我的视频剪辑运行对象检测时,它只需要大约 2 小时,但单个版本需要 18~24 小时。
    【解决方案2】:

    我从谷歌找到了这个教程 - creating-object-detection-application-tensorflow。在查看了它的github page --> object_detection_app --> app.py 之后,我们只需要在每次想要检测对象时运行 detect_objects(image_path) 函数。

    【讨论】:

    • 这给了我一个好主意。谢谢@BhanuKiran。我希望我的表现能有所提升。
    【解决方案3】:

    可以根据 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 更快。

    【讨论】:

      猜你喜欢
      • 2018-11-18
      • 1970-01-01
      • 2013-12-15
      • 2011-08-06
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 1970-01-01
      相关资源
      最近更新 更多