Как найти координаты маски объектов в API обнаружения объектов TensorFlow - PullRequest
0 голосов
/ 12 апреля 2020

Я использую этот код для получения выходных данных, используя маску модели rcnn (API обнаружения объектов Tensorflow). Мне удалось получить ограничивающие рамки координат обнаруженных объектов. Но когда я проверил массив, соответствующий маскам объектов, все записи были 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

1 Ответ

0 голосов
/ 19 апреля 2020

Значения массива, которые вы получаете, имеют множество нулей, за исключением случаев, когда существует маска, соответствующая тестируемому изображению, поэтому при печати output_dict ['detection_masks'] вы в основном видите 0 ценности. Пожалуйста, обратитесь к draw_mask_on_image_array function in visualization_utils.py , которая даст вам представление о том, как маска создается на изображении.

Ниже приведен фрагмент кода о том, как Вы можете визуализировать каждую маску:

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

Сохранение массива изображения в виде png, соответствующего pil_mask, даст вам изображение в оттенках серого с обнаруженной маской, а при сохранении массива изображения, соответствующего pil_image, вы получите составное цветное изображение с обнаруженной маской. .

Добавить, чтобы получить изображение со всеми масками:

np.copyto(image, np.array(pil_image.convert('RGB'))) 
...