models icon indicating copy to clipboard operation
models copied to clipboard

Unable to do "out-of-the-box" inference using the CenterNet Hourglass104 Keypoints Model - Object detection

Open Faiz-hmed opened this issue 6 years ago • 11 comments

I'm trying out the colab tutorials present in the object detction API, I was able to run inference on images using a saved model of the SSD mobile_net_v1 & with SSD ResNet101 v1. But while trying out this - https://github.com/tensorflow/models/blob/master/research/object_detection/colab_tutorials/inference_tf2_colab.ipynb

I encountered a key error [Due to the label map], after pointing the keypoints_label_map_path attribute in the pipeline.config file to the mscoco_label_map.pbtxt file in the data directory.

CODE

Changed MODELS dict from

'centernet_hg104_512x512_kpts_coco17_tpu-32' as in the official tutorial colab. to 👇

MODELS = {'centernet_with_keypoints': 'centernet_hourglass104_512x512_kpts_coco17_tpu-32', 'centernet_without_keypoints': 'centernet_hourglass104_512x512_coco17_tpu-8'}

model_display_name = 'centernet_with_keypoints'
model_name = MODELS[model_display_name] 
!pwd
if model_display_name == 'centernet_with_keypoints':
  !wget http://download.tensorflow.org/models/object_detection/tf2/20200711/centernet_hg104_512x512_kpts_coco17_tpu-32.tar.gz
  !tar -xf centernet_hg104_512x512_kpts_coco17_tpu-32.tar.gz
  !mv centernet_hg104_512x512_kpts_coco17_tpu-32/checkpoint models/research/object_detection/test_data/
else:
  !wget http://download.tensorflow.org/models/object_detection/tf2/20200711/centernet_hg104_512x512_coco17_tpu-8.tar.gz
  !tar -xf centernet_hg104_512x512_coco17_tpu-8.tar.gz
  !mv centernet_hg104_512x512_coco17_tpu-8/checkpoint models/research/object_detection/test_data/
pipeline_config = os.path.join('models/research/object_detection/configs/tf2/',
                                model_name + '.config')
print(pipeline_config)
model_dir = 'models/research/object_detection/test_data/checkpoint/'

# Load pipeline config and build a detection model
configs = config_util.get_configs_from_pipeline_file(pipeline_config)
model_config = configs['model']
detection_model = model_builder.build(model_config, is_training=False)

# Restore checkpoint
ckpt = tf.compat.v2.train.Checkpoint(
      model=detection_model)
ckpt.restore(os.path.join(model_dir, 'ckpt-0')).expect_partial()

def get_model_detection_function(model):
  """Get a tf.function for detection."""

  @tf.function
  def detect_fn(image):
    """Detect objects in image."""

    image, shapes = model.preprocess(image)
    prediction_dict = model.predict(image, shapes)
    detections = model.postprocess(prediction_dict, shapes)

    return detections, prediction_dict, tf.reshape(shapes, [-1])

  return detect_fn

detect_fn = get_model_detection_function(detection_model)

ERROR:

KeyError                                  Traceback (most recent call last)

<ipython-input-7-caea9ee6acd5> in <module>()
      7 configs = config_util.get_configs_from_pipeline_file(pipeline_config)
      8 model_config = configs['model']
----> 9 detection_model = model_builder.build(model_config, is_training=False)
     10 
     11 # Restore checkpoint


/usr/local/lib/python3.6/dist-packages/object_detection/builders/model_builder.py in build(model_config, is_training, add_summaries)
   1088     build_func = META_ARCH_BUILDER_MAP[meta_architecture]
   1089     return build_func(getattr(model_config, meta_architecture), is_training,
-> 1090                       add_summaries)

/usr/local/lib/python3.6/dist-packages/object_detection/builders/model_builder.py in _build_center_net_model(center_net_config, is_training, add_summaries)
    994     all_keypoint_indices = []
    995     for task in center_net_config.keypoint_estimation_task:
--> 996       kp_params = keypoint_proto_to_params(task, keypoint_map_dict)
    997       keypoint_params_dict[task.task_name] = kp_params
    998       all_keypoint_indices.extend(kp_params.keypoint_indices)

/usr/local/lib/python3.6/dist-packages/object_detection/builders/model_builder.py in keypoint_proto_to_params(kp_config, keypoint_map_dict)
    812 def keypoint_proto_to_params(kp_config, keypoint_map_dict):
    813   """Converts CenterNet.KeypointEstimation proto to parameter namedtuple."""
--> 814   label_map_item = keypoint_map_dict[kp_config.keypoint_class_name]
    815 
    816   classification_loss, localization_loss, _, _, _, _, _ = (

KeyError: '/m/01g317'

### PIPELINE.config file :

model {
  center_net {
    num_classes: 90
    feature_extractor {
      type: "hourglass_104"
      bgr_ordering: true
      channel_means: [104.01362025, 114.03422265, 119.9165958 ]
      channel_stds: [73.6027665 , 69.89082075, 70.9150767 ]
    }
    image_resizer {
      keep_aspect_ratio_resizer {
        min_dimension: 512
        max_dimension: 512
        pad_to_max_dimension: true
      }
    }
    object_detection_task {
      task_loss_weight: 1.0
      offset_loss_weight: 1.0
      scale_loss_weight: 0.1
      localization_loss {
        l1_localization_loss {
        }
      }
    }
    object_center_params {
      object_center_loss_weight: 1.0
      min_box_overlap_iou: 0.7
      max_box_predictions: 100
      classification_loss {
        penalty_reduced_logistic_focal_loss {
          alpha: 2.0
          beta: 4.0
        }
      }
    }

    keypoint_label_map_path: "/content/models/research/object_detection/data/mscoco_label_map.pbtxt"
    keypoint_estimation_task {
      task_name: "human_pose"
      task_loss_weight: 1.0
      loss {
        localization_loss {
          l1_localization_loss {
          }
        }
        classification_loss {
          penalty_reduced_logistic_focal_loss {
            alpha: 2.0
            beta: 4.0
          }
        }
      }
      keypoint_class_name: "/m/01g317"
      keypoint_label_to_std {
        key: "left_ankle"
        value: 0.89
      }
      keypoint_label_to_std {
        key: "left_ear"
        value: 0.35
      }
      keypoint_label_to_std {
        key: "left_elbow"
        value: 0.72
      }
      keypoint_label_to_std {
        key: "left_eye"
        value: 0.25
      }
      keypoint_label_to_std {
        key: "left_hip"
        value: 1.07
      }
      keypoint_label_to_std {
        key: "left_knee"
        value: 0.89
      }
      keypoint_label_to_std {
        key: "left_shoulder"
        value: 0.79
      }
      keypoint_label_to_std {
        key: "left_wrist"
        value: 0.62
      }
      keypoint_label_to_std {
        key: "nose"
        value: 0.26
      }
      keypoint_label_to_std {
        key: "right_ankle"
        value: 0.89
      }
      keypoint_label_to_std {
        key: "right_ear"
        value: 0.35
      }
      keypoint_label_to_std {
        key: "right_elbow"
        value: 0.72
      }
      keypoint_label_to_std {
        key: "right_eye"
        value: 0.25
      }
      keypoint_label_to_std {
        key: "right_hip"
        value: 1.07
      }
      keypoint_label_to_std {
        key: "right_knee"
        value: 0.89
      }
      keypoint_label_to_std {
        key: "right_shoulder"
        value: 0.79
      }
      keypoint_label_to_std {
        key: "right_wrist"
        value: 0.62
      }
      keypoint_regression_loss_weight: 0.1
      keypoint_heatmap_loss_weight: 1.0
      keypoint_offset_loss_weight: 1.0
      offset_peak_radius: 3
      per_keypoint_offset: true
    }
  }
}

Why is this error being thrown? Should there be any changes made to the label map? Any help would be greatly appreciated @tombstone @jch1 @pkulzc Any clue about this? PS: I'm running on google Colab with tensorflow version 2.3. pip version : 20.0.4

Faiz-hmed avatar Nov 26 '20 11:11 Faiz-hmed

I change keypoint_class_name: "/m/01g317" into keypoint_class_name: "Person"

hhsinhan avatar Nov 26 '20 11:11 hhsinhan

But there are multiple classes with those codes

this is a sample of the label map:

item {
  name: "background"
  id: 0
  display_name: "background"
}
item {
  name: "/m/01g317"
  id: 1
  display_name: "person"
}
item {
  name: "/m/0199g"
  id: 2
  display_name: "bicycle"
}
item {
  name: "/m/0k4j"
  id: 3
  display_name: "car"
}
item {
  name: "/m/04_sv"
  id: 4
  display_name: "motorcycle"
}
item {
  name: "/m/05czz6l"
  id: 5
  display_name: "airplane"
}
item {
  name: "/m/01bjv"
  id: 6
  display_name: "bus"
}
item {
  name: "/m/07jdr"
  id: 7
  display_name: "train"
}
item {
  name: "/m/07r04"
  id: 8
  display_name: "truck"
}
item {
  name: "/m/019jd"
  id: 9
  display_name: "boat"
}
item {
  name: "/m/015qff"
  id: 10
  display_name: "traffic light"
}
item {
  name: "/m/01pns0"
  id: 11
  display_name: "fire hydrant"
}
item {
  name: "12"
  id: 12
  display_name: "12"
}
item {
  name: "/m/02pv19"
  id: 13
  display_name: "stop sign"
}
item {
  name: "/m/015qbp"
  id: 14
  display_name: "parking meter"
}
item {
  name: "/m/0cvnqh"
  id: 15
  display_name: "bench"
}
item {
  name: "/m/015p6"
  id: 16
  display_name: "bird"
}
item {
  name: "/m/01yrx"
  id: 17
  display_name: "cat"
}
item {
  name: "/m/0bt9lr"
  id: 18
  display_name: "dog"
}
item {
  name: "/m/03k3r"
  id: 19
  display_name: "horse"
}
item {
  name: "/m/07bgp"
  id: 20
  display_name: "sheep"
}

Notice how the 12th item has the name same as it's id. Is there a specific reason for that?

Faiz-hmed avatar Nov 26 '20 16:11 Faiz-hmed

I change keypoint_class_name: "/m/01g317" into keypoint_class_name: "Person"

Still not work... it returns KeyError: 'Person', is there any other place need to be updated?

Neway6655 avatar Jan 06 '21 06:01 Neway6655

I change keypoint_class_name: "/m/01g317" into keypoint_class_name: "Person"

Still not work... it returns KeyError: 'Person', is there any other place need to be updated?

what keypoint_label_map_path you put inside?

hhsinhan avatar Jan 06 '21 07:01 hhsinhan

I change keypoint_class_name: "/m/01g317" into keypoint_class_name: "Person"

Still not work... it returns KeyError: 'Person', is there any other place need to be updated?

what keypoint_label_map_path you put inside?

models/research/object_detection/data/mscoco_label_map.pbtxt

Neway6655 avatar Jan 06 '21 09:01 Neway6655

I change keypoint_class_name: "/m/01g317" into keypoint_class_name: "Person"

Still not work... it returns KeyError: 'Person', is there any other place need to be updated?

what keypoint_label_map_path you put inside?

models/research/object_detection/data/mscoco_label_map.pbtxt

can you try this pbtxt instead? models/research/object_detection/data/face_person_with_keypoints_label_map.pbtxt

hhsinhan avatar Jan 06 '21 09:01 hhsinhan

I change keypoint_class_name: "/m/01g317" into keypoint_class_name: "Person"

Still not work... it returns KeyError: 'Person', is there any other place need to be updated?

what keypoint_label_map_path you put inside?

models/research/object_detection/data/mscoco_label_map.pbtxt

can you try this pbtxt instead? models/research/object_detection/data/face_person_with_keypoints_label_map.pbtxt

it worked, thanks.

Neway6655 avatar Jan 06 '21 09:01 Neway6655

@Neway6655 Closing this issue since the issue was resolved. Please feel free to reopen the issue if you have any concern, Thanks!

saikumarchalla avatar Jan 10 '21 14:01 saikumarchalla

Are you satisfied with the resolution of your issue? Yes No

google-ml-butler[bot] avatar Jan 10 '21 14:01 google-ml-butler[bot]

@saikumarchalla @Neway6655 I still get an error however a different one -

Code:

I'm using the same model and checkpoint as before, changed the label_map and class_name to "Person" accordingly.


#Testing on image from test_images folder
image_dir = '/home/ubuntu/mayub/Tensorflow/models/research/object_detection/test_images/'
image_path = os.path.join(image_dir, 'image2.jpg')
image_np = load_image_into_numpy_array(image_path)

input_tensor = tf.convert_to_tensor(
    np.expand_dims(image_np, 0), dtype=tf.float32)
detections, predictions_dict, shapes = detect_fn(input_tensor)

Error:

TypeError                                 Traceback (most recent call last)
<ipython-input-26-53d3633f8f72> in <module>
     13 input_tensor = tf.convert_to_tensor(
     14     np.expand_dims(image_np, 0), dtype=tf.float32)
---> 15 detections, predictions_dict, shapes = detect_fn(input_tensor)
     16 
     17 label_id_offset = 1

~/anaconda3/envs/tensorflow2_p36/lib/python3.6/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)
    578         xla_context.Exit()
    579     else:
--> 580       result = self._call(*args, **kwds)
    581 
    582     if tracing_count == self._get_tracing_count():

~/anaconda3/envs/tensorflow2_p36/lib/python3.6/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)
    625       # This is the first call of __call__, so we have to initialize.
    626       initializers = []
--> 627       self._initialize(args, kwds, add_initializers_to=initializers)
    628     finally:
    629       # At this point we know that the initialization is complete (or less

~/anaconda3/envs/tensorflow2_p36/lib/python3.6/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)
    504     self._concrete_stateful_fn = (
    505         self._stateful_fn._get_concrete_function_internal_garbage_collected(  # pylint: disable=protected-access
--> 506             *args, **kwds))
    507 
    508     def invalid_creator_scope(*unused_args, **unused_kwds):

~/anaconda3/envs/tensorflow2_p36/lib/python3.6/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)
   2444       args, kwargs = None, None
   2445     with self._lock:
-> 2446       graph_function, _, _ = self._maybe_define_function(args, kwargs)
   2447     return graph_function
   2448 

~/anaconda3/envs/tensorflow2_p36/lib/python3.6/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)
   2775 
   2776       self._function_cache.missed.add(call_context_key)
-> 2777       graph_function = self._create_graph_function(args, kwargs)
   2778       self._function_cache.primary[cache_key] = graph_function
   2779       return graph_function, args, kwargs

~/anaconda3/envs/tensorflow2_p36/lib/python3.6/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)
   2665             arg_names=arg_names,
   2666             override_flat_arg_shapes=override_flat_arg_shapes,
-> 2667             capture_by_value=self._capture_by_value),
   2668         self._function_attributes,
   2669         # Tell the ConcreteFunction to clean up its graph once it goes out of

~/anaconda3/envs/tensorflow2_p36/lib/python3.6/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)
    979         _, original_func = tf_decorator.unwrap(python_func)
    980 
--> 981       func_outputs = python_func(*func_args, **func_kwargs)
    982 
    983       # invariant: `func_outputs` contains only Tensors, CompositeTensors,

~/anaconda3/envs/tensorflow2_p36/lib/python3.6/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)
    439         # __wrapped__ allows AutoGraph to swap in a converted function. We give
    440         # the function a weak reference to itself to avoid a reference cycle.
--> 441         return weak_wrapped_fn().__wrapped__(*args, **kwds)
    442     weak_wrapped_fn = weakref.ref(wrapped_fn)
    443 

~/anaconda3/envs/tensorflow2_p36/lib/python3.6/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
    966           except Exception as e:  # pylint:disable=broad-except
    967             if hasattr(e, "ag_error_metadata"):
--> 968               raise e.ag_error_metadata.to_exception(e)
    969             else:
    970               raise

TypeError: in user code:

    <ipython-input-17-04098793256e>:27 detect_fn  *
        detections = model.postprocess(prediction_dict, shapes)
    /home/ubuntu/anaconda3/envs/tensorflow2_p36/lib/python3.6/site-packages/object_detection/meta_architectures/center_net_meta_arch.py:2945 postprocess  *
        keypoints, keypoint_scores = (
    /home/ubuntu/anaconda3/envs/tensorflow2_p36/lib/python3.6/site-packages/object_detection/meta_architectures/center_net_meta_arch.py:1086 convert_strided_predictions_to_normalized_keypoints  *
        keypoint_coords_normalized = tf.map_fn(

    TypeError: map_fn() got an unexpected keyword argument 'fn_output_signature'

mohammedayub44 avatar Jan 14 '21 01:01 mohammedayub44

@Faiz-hmed Could you please submit a new issue so that we can track it separately. Thanks!

saikumarchalla avatar Jan 18 '21 16:01 saikumarchalla