如何在TensorFlow对象检测API中查找对象的蒙版坐标

问题描述 投票:0回答:1

我正在使用此代码通过mask rcnn模型(Tensorflow对象检测API)获取输出。我能够检索检测到的对象的边界框坐标。但是,当我检查与对象蒙版相对应的数组时,每个检测到的对象的所有条目均为0。我该怎么做才能获得与检测到的对象的蒙版相对应的数组


def run_inference_for_single_image(image, graph):
  with graph.as_default():
    with tf.Session() as sess:
      # Get handles to input and output tensors
      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:
        # The following processing is only for single image
        detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
        detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
        # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
        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[1], image.shape[2])
        detection_masks_reframed = tf.cast(
            tf.greater(detection_masks_reframed, 0.5), tf.uint8)
        # Follow the convention by adding back the batch dimension
        tensor_dict['detection_masks'] = tf.expand_dims(
            detection_masks_reframed, 0)
      image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')

      # Run inference
      output_dict = sess.run(tensor_dict,
                             feed_dict={image_tensor: image})

      # all outputs are float32 numpy arrays, so convert types as appropriate
      print(output_dict['num_detections'].shape)
      print(output_dict['num_detections'])
      print(output_dict['detection_classes'].shape)
      print(output_dict['detection_classes'])
      print(output_dict['detection_boxes'].shape)
      print(output_dict['detection_boxes'])
      print(output_dict['detection_scores'].shape)
      print(output_dict['detection_scores'])
      print(output_dict['detection_masks'].shape)
      print(output_dict['detection_masks'])
      output_dict['num_detections'] = int(output_dict['num_detections'][0])
      output_dict['detection_classes'] = output_dict[
          'detection_classes'][0].astype(np.int64)
      output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
      output_dict['detection_scores'] = output_dict['detection_scores'][0]
      if 'detection_masks' in output_dict:
        output_dict['detection_masks'] = output_dict['detection_masks'][0]
  return output_dict

python tensorflow computer-vision image-segmentation object-detection-api
1个回答
0
投票

您得到的数组值有很多0,除非有与要测试的图像相对应的遮罩,因此在打印output_dict ['detection_masks']时,您通常会看到0值。请参考visualization_utils.py中的draw_mask_on_image_array函数,它将使您了解如何在图像上创建蒙版。

下面是有关如何可视化每个蒙版的代码段:

box_to_instance_masks_map = {}
for j in range(max_boxes_to_draw):
    if output_dict['detection_scores'][j] > min_score_thresh: 
        box = tuple(output_dict['detection_boxes'][j].tolist())
        box_to_instance_masks_map[box] = output_dict.['detection_masks'][j]
        mask = box_to_instance_masks_map[box]

        rgb = ImageColor.getrgb('red')
        pil_image = Image.fromarray(image_np)

        solid_color = np.expand_dims(np.ones_like(mask), axis=2) * np.reshape(list(rgb), [1, 1, 3])
        pil_solid_color = Image.fromarray(np.uint8(solid_color)).convert('RGBA')
        pil_mask = Image.fromarray(np.uint8(255.0*1.0*mask)).convert('L')
        pil_image = Image.composite(pil_solid_color, pil_image, pil_mask)

        vis_util.save_image_array_as_png(pil_mask, 'your file path')
        vis_util.save_image_array_as_png(pil_image, 'your file path')

将与pil_mask对应的图像数组另存为png将为您提供带有检测到的蒙版的灰度图像,而与pil_image相对应的图像数组将为您提供带有检测到的蒙版的彩色复合图像。

添加以获得带有所有蒙版的图像:

np.copyto(image, np.array(pil_image.convert('RGB'))) 
© www.soinside.com 2019 - 2024. All rights reserved.