当前位置: 首页>>代码示例>>Python>>正文


Python label_map_util.create_category_index方法代码示例

本文整理汇总了Python中object_detection.utils.label_map_util.create_category_index方法的典型用法代码示例。如果您正苦于以下问题:Python label_map_util.create_category_index方法的具体用法?Python label_map_util.create_category_index怎么用?Python label_map_util.create_category_index使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在object_detection.utils.label_map_util的用法示例。


在下文中一共展示了label_map_util.create_category_index方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: load_model

# 需要导入模块: from object_detection.utils import label_map_util [as 别名]
# 或者: from object_detection.utils.label_map_util import create_category_index [as 别名]
def load_model(self):
        """
        Loads the detection model

        Args:

        Returns:

        """

        with self._detection_graph.as_default():
            od_graph_def = tf.GraphDef()
            with tf.gfile.GFile(self._path_to_ckpt, 'rb') as fid:
                serialized_graph = fid.read()
                od_graph_def.ParseFromString(serialized_graph)
                tf.import_graph_def(od_graph_def, name='')

        label_map = label_map_util.load_labelmap(self._path_to_labels)
        categories = label_map_util.convert_label_map_to_categories(\
            label_map, max_num_classes=self._num_classes, use_display_name=True)
        self.category_index = label_map_util.create_category_index(categories) 
开发者ID:cagbal,项目名称:ros_people_object_detection_tensorflow,代码行数:23,代码来源:detector.py

示例2: load_details

# 需要导入模块: from object_detection.utils import label_map_util [as 别名]
# 或者: from object_detection.utils.label_map_util import create_category_index [as 别名]
def load_details(args):

    PATH_TO_CKPT = args.frozen_graph
    PATH_TO_LABELS = args.label_map
    NUM_CLASSES = args.num_output_classes
    PATH_TO_TEST_IMAGES_DIR = args.input_dir
    PATH_TO_RESULT_IMAGES_DIR = args.output_dir

    if not os.path.exists(args.output_dir):
        os.mkdir(args.output_dir)

    TEST_IMAGE_PATHS = sorted(glob.glob(os.path.join(PATH_TO_TEST_IMAGES_DIR, '*.jpg')))
    JPG_PATHS = [ os.path.basename(path) for path in TEST_IMAGE_PATHS ]
    RESULT_IMAGE_PATHS = [ os.path.join(PATH_TO_RESULT_IMAGES_DIR, jpg_path) for jpg_path in JPG_PATHS ]

    label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
    categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
    category_index = label_map_util.create_category_index(categories)

    return TEST_IMAGE_PATHS, RESULT_IMAGE_PATHS, category_index 
开发者ID:rj97,项目名称:Accident-Detection-on-Indian-Roads,代码行数:22,代码来源:inference.py

示例3: test_create_category_index

# 需要导入模块: from object_detection.utils import label_map_util [as 别名]
# 或者: from object_detection.utils.label_map_util import create_category_index [as 别名]
def test_create_category_index(self):
    categories = [{'name': u'1', 'id': 1}, {'name': u'2', 'id': 2}]
    category_index = label_map_util.create_category_index(categories)
    self.assertDictEqual({
        1: {
            'name': u'1',
            'id': 1
        },
        2: {
            'name': u'2',
            'id': 2
        }
    }, category_index) 
开发者ID:datitran,项目名称:object_detector_app,代码行数:15,代码来源:label_map_util_test.py

示例4: load

# 需要导入模块: from object_detection.utils import label_map_util [as 别名]
# 或者: from object_detection.utils.label_map_util import create_category_index [as 别名]
def load(self):
		with open(os.path.join(self.model_path, 'config.json')) as f:
			data = json.load(f)
		try:
			self.validate_json_configuration(data)
			self.set_model_configuration(data)
		except ApplicationError as e:
			raise e

		self.label_path = os.path.join(self.model_path, 'object-detection.pbtxt')
		self.label_map = label_map_util.load_labelmap(self.label_path)
		self.categories = label_map_util.convert_label_map_to_categories(self.label_map,
																		 max_num_classes=self.NUM_CLASSES,
																		 use_display_name=True)
		for dict in self.categories:
			self.labels.append(dict['name'])

		self.category_index = label_map_util.create_category_index(self.categories)
		self.detection_graph = tf.Graph()
		with self.detection_graph.as_default():
			od_graph_def = tf.GraphDef()
			with tf.gfile.GFile(os.path.join(self.model_path, 'frozen_inference_graph.pb'), 'rb') as fid:
				serialized_graph = fid.read()
				od_graph_def.ParseFromString(serialized_graph)
				tf.import_graph_def(od_graph_def, name='')
			self.image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0')
			self.d_boxes = self.detection_graph.get_tensor_by_name('detection_boxes:0')
			self.d_scores = self.detection_graph.get_tensor_by_name('detection_scores:0')
			self.d_classes = self.detection_graph.get_tensor_by_name('detection_classes:0')
			self.num_d = self.detection_graph.get_tensor_by_name('num_detections:0')
		self.sess = tf.Session(graph=self.detection_graph)
		img = Image.open("object_detection/image1.jpg")
		img_expanded = np.expand_dims(img, axis=0)
		self.sess.run(
			[self.d_boxes, self.d_scores, self.d_classes, self.num_d],
			feed_dict={self.image_tensor: img_expanded}) 
开发者ID:BMW-InnovationLab,项目名称:BMW-TensorFlow-Inference-API-CPU,代码行数:38,代码来源:tensorflow_detection.py

示例5: evaluate

# 需要导入模块: from object_detection.utils import label_map_util [as 别名]
# 或者: from object_detection.utils.label_map_util import create_category_index [as 别名]
def evaluate(self):
    """Compute evaluation result.

    Returns:
      A dictionary of metrics with the following fields -

      1. summary_metrics:
        'Precision/mAP@<matching_iou_threshold>IOU': mean average precision at
        the specified IOU threshold.

      2. per_category_ap: category specific results with keys of the form
        'PerformanceByCategory/mAP@<matching_iou_threshold>IOU/category'.
    """
    (per_class_ap, mean_ap, _, _, per_class_corloc, mean_corloc) = (
        self._evaluation.evaluate())
    pascal_metrics = {
        self._metric_prefix +
        'Precision/mAP@{}IOU'.format(self._matching_iou_threshold):
            mean_ap
    }
    if self._evaluate_corlocs:
      pascal_metrics[self._metric_prefix + 'Precision/meanCorLoc@{}IOU'.format(
          self._matching_iou_threshold)] = mean_corloc
    category_index = label_map_util.create_category_index(self._categories)
    for idx in range(per_class_ap.size):
      if idx + self._label_id_offset in category_index:
        display_name = (
            self._metric_prefix + 'PerformanceByCategory/AP@{}IOU/{}'.format(
                self._matching_iou_threshold,
                category_index[idx + self._label_id_offset]['name']))
        pascal_metrics[display_name] = per_class_ap[idx]

        # Optionally add CorLoc metrics.classes
        if self._evaluate_corlocs:
          display_name = (
              self._metric_prefix + 'PerformanceByCategory/CorLoc@{}IOU/{}'
              .format(self._matching_iou_threshold,
                      category_index[idx + self._label_id_offset]['name']))
          pascal_metrics[display_name] = per_class_corloc[idx]

    return pascal_metrics 
开发者ID:cagbal,项目名称:ros_people_object_detection_tensorflow,代码行数:43,代码来源:object_detection_evaluation.py

示例6: format_output

# 需要导入模块: from object_detection.utils import label_map_util [as 别名]
# 或者: from object_detection.utils.label_map_util import create_category_index [as 别名]
def format_output(self, results, im_width, im_height, threshold):
        label_map = label_map_util.load_labelmap(self.label_map)
        categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=90, use_display_name=True)
        category_index = label_map_util.create_category_index(categories)
        vis_results = []
        for i in range(len(results)):
            output_dict = results[i]
            boxes = output_dict['detection_boxes']
            classes = output_dict['detection_classes']
            scores = output_dict['detection_scores']
            for j in range(boxes.shape[0]):
                if scores[i] > threshold:
                    result = {}
                    ymin, xmin, ymax, xmax = tuple(boxes[i].tolist())
                    result['x_min'] = xmin * im_width
                    result['x_max'] = xmax * im_width
                    result['y_min'] = ymin * im_height
                    result['y_max'] = ymax * im_height
                    result['score'] = float(scores[i])
                    if classes[i] in category_index.keys():
                        class_name = category_index[classes[i]]['name']
                    else:
                        class_name = 'N/A'
                    result['class_name'] = str(class_name)
                    if result not in vis_results:
                        vis_results.append(result)
        return vis_results 
开发者ID:autoai-org,项目名称:CVTron,代码行数:29,代码来源:slim_object_detector.py

示例7: load

# 需要导入模块: from object_detection.utils import label_map_util [as 别名]
# 或者: from object_detection.utils.label_map_util import create_category_index [as 别名]
def load(self):
        with open(os.path.join(self.model_path, 'config.json')) as f:
            data = json.load(f)
        try:
            self.validate_json_configuration(data)
            self.set_configuration(data)
        except ApplicationError as e:
            raise e

        self.label_path = os.path.join(self.model_path, 'object-detection.pbtxt')
        self.label_map = label_map_util.load_labelmap(self.label_path)
        self.categories = label_map_util.convert_label_map_to_categories(self.label_map,
                                                                         max_num_classes=self.NUM_CLASSES,
                                                                         use_display_name=True)
        for dict in self.categories:
            self.labels.append(dict['name'])

        self.category_index = label_map_util.create_category_index(self.categories)
        self.detection_graph = tf.Graph()
        with self.detection_graph.as_default():
            od_graph_def = tf.GraphDef()
            with tf.gfile.GFile(os.path.join(self.model_path, 'frozen_inference_graph.pb'), 'rb') as fid:
                serialized_graph = fid.read()
                od_graph_def.ParseFromString(serialized_graph)
                tf.import_graph_def(od_graph_def, name='')
            self.image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0')
            self.d_boxes = self.detection_graph.get_tensor_by_name('detection_boxes:0')
            self.d_scores = self.detection_graph.get_tensor_by_name('detection_scores:0')
            self.d_classes = self.detection_graph.get_tensor_by_name('detection_classes:0')
            self.num_d = self.detection_graph.get_tensor_by_name('num_detections:0')
        self.sess = tf.Session(graph=self.detection_graph)
        img = Image.open("object_detection/image1.jpg")
        img_expanded = np.expand_dims(img, axis=0)
        (boxes, scores, classes, num) = self.sess.run(
            [self.d_boxes, self.d_scores, self.d_classes, self.num_d],
            feed_dict={self.image_tensor: img_expanded}) 
开发者ID:BMW-InnovationLab,项目名称:BMW-TensorFlow-Training-GUI,代码行数:38,代码来源:tensorflow_detection.py

示例8: _build_metric_names

# 需要导入模块: from object_detection.utils import label_map_util [as 别名]
# 或者: from object_detection.utils.label_map_util import create_category_index [as 别名]
def _build_metric_names(self):
    """Builds a list with metric names."""

    self._metric_names = [
        self._metric_prefix + 'Precision/mAP@{}IOU'.format(
            self._matching_iou_threshold)
    ]
    if self._evaluate_corlocs:
      self._metric_names.append(
          self._metric_prefix +
          'Precision/meanCorLoc@{}IOU'.format(self._matching_iou_threshold))

    category_index = label_map_util.create_category_index(self._categories)
    for idx in range(self._num_classes):
      if idx + self._label_id_offset in category_index:
        category_name = category_index[idx + self._label_id_offset]['name']
        try:
          #category_name = unicode(category_name, 'utf-8')
          category_name = str(category_name, 'utf-8')
        except TypeError:
          pass
        category_name = unicodedata.normalize('NFKD', category_name).encode(
            'ascii', 'ignore')
        self._metric_names.append(
            self._metric_prefix + 'PerformanceByCategory/AP@{}IOU/{}'.format(
                self._matching_iou_threshold, category_name))
        if self._evaluate_corlocs:
          self._metric_names.append(
              self._metric_prefix + 'PerformanceByCategory/CorLoc@{}IOU/{}'
              .format(self._matching_iou_threshold, category_name)) 
开发者ID:PINTO0309,项目名称:TPU-MobilenetSSD,代码行数:32,代码来源:object_detection_evaluation.py

示例9: _build_metric_names

# 需要导入模块: from object_detection.utils import label_map_util [as 别名]
# 或者: from object_detection.utils.label_map_util import create_category_index [as 别名]
def _build_metric_names(self):
    """Builds a list with metric names."""
    if self._recall_lower_bound > 0.0 or self._recall_upper_bound < 1.0:
      self._metric_names = [
          self._metric_prefix +
          'Precision/mAP@{}IOU@[{:.1f},{:.1f}]Recall'.format(
              self._matching_iou_threshold, self._recall_lower_bound,
              self._recall_upper_bound)
      ]
    else:
      self._metric_names = [
          self._metric_prefix +
          'Precision/mAP@{}IOU'.format(self._matching_iou_threshold)
      ]
    if self._evaluate_corlocs:
      self._metric_names.append(
          self._metric_prefix +
          'Precision/meanCorLoc@{}IOU'.format(self._matching_iou_threshold))

    category_index = label_map_util.create_category_index(self._categories)
    for idx in range(self._num_classes):
      if idx + self._label_id_offset in category_index:
        category_name = category_index[idx + self._label_id_offset]['name']
        try:
          category_name = six.text_type(category_name, 'utf-8')
        except TypeError:
          pass
        category_name = unicodedata.normalize('NFKD', category_name)
        if six.PY2:
          category_name = category_name.encode('ascii', 'ignore')
        self._metric_names.append(
            self._metric_prefix + 'PerformanceByCategory/AP@{}IOU/{}'.format(
                self._matching_iou_threshold, category_name))
        if self._evaluate_corlocs:
          self._metric_names.append(
              self._metric_prefix +
              'PerformanceByCategory/CorLoc@{}IOU/{}'.format(
                  self._matching_iou_threshold, category_name)) 
开发者ID:ShivangShekhar,项目名称:Live-feed-object-device-identification-using-Tensorflow-and-OpenCV,代码行数:40,代码来源:object_detection_evaluation.py

示例10: __init__

# 需要导入模块: from object_detection.utils import label_map_util [as 别名]
# 或者: from object_detection.utils.label_map_util import create_category_index [as 别名]
def __init__(self):
        logger.info('Loading Tensorflow Detection API')

        weights_path = get_file(config.SSD_INCEPTION_FILENAME, config.SSD_INCEPTION_URL,
                                cache_dir=os.path.abspath(config.WEIGHT_PATH),
                                cache_subdir='models')

        extract_path = weights_path.replace('.tar.gz', '')
        if not os.path.exists(extract_path):
            tar = tarfile.open(weights_path, "r:gz")
            tar.extractall(path=os.path.join(config.WEIGHT_PATH, 'models'))
            tar.close()
        pb_path = os.path.join(extract_path, self.PB_NAME)

        self.graph = tf.Graph()
        with self.graph.as_default():
            od_graph_def = tf.GraphDef()
            with tf.gfile.GFile(pb_path, 'rb') as fid:
                serialized_graph = fid.read()
                od_graph_def.ParseFromString(serialized_graph)
                tf.import_graph_def(od_graph_def, name='')

        self.label_map = label_map_util.load_labelmap(self.PATH_TO_LABELS)
        self.categories = label_map_util.convert_label_map_to_categories(self.label_map,
                                                                         max_num_classes=self.NUM_CLASSES,
                                                                         use_display_name=True)
        self.category_index = label_map_util.create_category_index(self.categories) 
开发者ID:EliotAndres,项目名称:pretrained.ml,代码行数:29,代码来源:models.py


注:本文中的object_detection.utils.label_map_util.create_category_index方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。