Tensorflow 对象检测 API 裁剪图像片段

Tensorflow Object Detection API cropping segments of an image

我将 Tensorflow 对象检测 API 与可以检测带有边界框和遮罩的对象的模型一起使用。

这是我的代码:

def run_inference_for_single_image_raw(image, graph):
  with graph.as_default():
    with tf.Session() as sess:
      ops = tf.get_default_graph().get_operations()
      all_tensor_names = {output.name for op in ops for output in op.outputs}
      tensor_dict = {}
      for key in [
          'num_detections', 'detection_boxes', 'detection_scores',
          'detection_classes', 'detection_masks'
      ]:
        tensor_name = key + ':0'
        if tensor_name in all_tensor_names:
          tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(
              tensor_name)
      if 'detection_masks' in tensor_dict:
        detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
        detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
        real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
        detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
        detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
        detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
            detection_masks, detection_boxes, image.shape[0], image.shape[1])
        detection_masks_reframed = tf.cast(
            tf.greater(detection_masks_reframed, 0.5), tf.uint8)
        tensor_dict['detection_masks'] = tf.expand_dims(
            detection_masks_reframed, 0)
      image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')

      output_dict = sess.run(tensor_dict,
                             feed_dict={image_tensor: np.expand_dims(image, 0)})

  return output_dict

所以如果我 运行 下面的代码:

vis_util.visualize_boxes_and_labels_on_image_array(
      image,
      output_dict['detection_boxes'],
      output_dict['detection_classes'],
      output_dict['detection_scores'],
      category_index,
      instance_masks=output_dict.get('detection_masks'),
      use_normalized_coordinates=True,
      line_thickness=8)
plt.figure(figsize=(12, 8))
plt.grid(False)
plt.imshow(image)

结果是(带有边界框和遮罩的图像):

那么,我如何通过遮罩路径裁剪图像对象,而不是边界框,所以在这个例子中我只想输出带有对象的图像(cat/bottle) 在透明背景上。 (可能正在使用 PIL 或 OpenCV 等)

因此,如果output_dict.get('detection_masks') 是 numpy 对象并且实际上是二进制掩码,您可以通过简单地乘以或使用 np.where

来裁剪图像
mask = output_dict.get('detection_masks')
img_cropped = img * mask

这将裁剪所有检测到的对象,但如果您想单独裁剪对象,可以通过检测轮廓来实现。我们可以为此使用 scikit-image

from skimage import measure
label_mask = measure.label(mask)

我们现在已经标记了二进制图像中的所有连接组件,并为每个组件分配了数字标签(通过更改像素值)。标签从“1”开始,以对象数结束。

single_object_mask = (label_mask == 1) #or 2, 3...

这将使用您提供的标签过滤 label_mask 图像。您还可以使用边界框信息裁剪特定对象。