Получите координаты ограничивающей рамки в руководстве по API обнаружения объектов TensorFlow.

Я новичок как в Python, так и в Tensorflow. Я пытаюсь запустить файл object_detection_tutorial из API обнаружения объектов Tensorflow, но я не могу найти, где я могу получить координаты ограничивающих рамок при обнаружении объектов.

Соответствующий код:

 # 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])

...

Место, где, как я предполагаю, нарисованы ограничивающие рамки, выглядит следующим образом:

 # Visualization of the results of a detection.
  vis_util.visualize_boxes_and_labels_on_image_array(
      image_np,
      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=IMAGE_SIZE)
  plt.imshow(image_np)

Я попытался распечатать output_dict ['detect_boxes'], но не уверен, что означают числа. Много.

array([[ 0.56213236,  0.2780568 ,  0.91445708,  0.69120586],
       [ 0.56261235,  0.86368728,  0.59286624,  0.8893863 ],
       [ 0.57073039,  0.87096912,  0.61292225,  0.90354401],
       [ 0.51422435,  0.78449738,  0.53994244,  0.79437423],

......

   [ 0.32784131,  0.5461576 ,  0.36972913,  0.56903434],
   [ 0.03005961,  0.02714229,  0.47211722,  0.44683522],
   [ 0.43143299, 0.09211366,  0.58121657,  0.3509962 ]], dtype=float32)

Я нашел ответы на похожие вопросы, но у меня нет такой переменной, как они. Как я могу получить координаты? Спасибо!


person Mandy    schedule 21.02.2018    source источник


Ответы (3)


Я пробовал распечатать output_dict ['detect_boxes'], но не уверен, что означают числа

Вы можете сами проверить код. visualize_boxes_and_labels_on_image_array определяется здесь.

Обратите внимание, что вы передаете use_normalized_coordinates=True. Если вы отслеживаете вызовы функций, вы увидите, что ваши числа [ 0.56213236, 0.2780568 , 0.91445708, 0.69120586] и т. Д. Являются значениями [ymin, xmin, ymax, xmax], где координаты изображения:

(left, right, top, bottom) = (xmin * im_width, xmax * im_width, 
                              ymin * im_height, ymax * im_height)

вычисляются функцией:

def draw_bounding_box_on_image(image,
                           ymin,
                           xmin,
                           ymax,
                           xmax,
                           color='red',
                           thickness=4,
                           display_str_list=(),
                           use_normalized_coordinates=True):
  """Adds a bounding box to an image.
  Bounding box coordinates can be specified in either absolute (pixel) or
  normalized coordinates by setting the use_normalized_coordinates argument.
  Each string in display_str_list is displayed on a separate line above the
  bounding box in black text on a rectangle filled with the input 'color'.
  If the top of the bounding box extends to the edge of the image, the strings
  are displayed below the bounding box.
  Args:
    image: a PIL.Image object.
    ymin: ymin of bounding box.
    xmin: xmin of bounding box.
    ymax: ymax of bounding box.
    xmax: xmax of bounding box.
    color: color to draw bounding box. Default is red.
    thickness: line thickness. Default value is 4.
    display_str_list: list of strings to display in box
                      (each to be shown on its own line).
    use_normalized_coordinates: If True (default), treat coordinates
      ymin, xmin, ymax, xmax as relative to the image.  Otherwise treat
      coordinates as absolute.
  """
  draw = ImageDraw.Draw(image)
  im_width, im_height = image.size
  if use_normalized_coordinates:
    (left, right, top, bottom) = (xmin * im_width, xmax * im_width,
                                  ymin * im_height, ymax * im_height)
person MFisherKDX    schedule 21.02.2018
comment
Хорошо. Кажется, что output_dict ['detect_boxes'] содержит все перекрывающиеся блоки, и поэтому существует так много массивов. Спасибо! - person Mandy; 22.02.2018
comment
Что определяет количество перекрывающихся блоков? А также почему так много перекрывающихся блоков, почему это передается на слой визуализации для слияния? - person CMCDragonkai; 08.03.2018
comment
Я знаю, что это старый вопрос, но я подумал, что это может кому-то помочь. Вы можете ограничить количество перекрывающихся блоков, если увеличите min_score_thresh во входных переменных visualize_boxes_and_labels_on_image_array функции. По умолчанию он установлен на 0.5, например, для моего проекта мне пришлось увеличить это значение до 0.8. - person Hensler Software; 03.05.2019

У меня точно такая же история. Получил массив примерно с сотней блоков (output_dict['detection_boxes']), когда на изображении отображался только один. Углубившись в код, который рисует прямоугольник, удалось извлечь его и использовать в моем inference.py:

#so detection has happened and you've got output_dict as a
# result of your inference

# then assume you've got this in your inference.py in order to draw rectangles
vis_util.visualize_boxes_and_labels_on_image_array(
    image_np,
    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)

# This is the way I'm getting my coordinates
boxes = output_dict['detection_boxes']
# get all boxes from an array
max_boxes_to_draw = boxes.shape[0]
# get scores to get a threshold
scores = output_dict['detection_scores']
# this is set as a default but feel free to adjust it to your needs
min_score_thresh=.5
# iterate over all objects found
for i in range(min(max_boxes_to_draw, boxes.shape[0])):
    # 
    if scores is None or scores[i] > min_score_thresh:
        # boxes[i] is the box which will be drawn
        class_name = category_index[output_dict['detection_classes'][i]]['name']
        print ("This box is gonna get used", boxes[i], output_dict['detection_classes'][i])
person Vadim    schedule 19.06.2019

Приведенный выше ответ не сработал для меня, мне пришлось внести некоторые изменения. Так что, если это не поможет, попробуйте это.

# This is the way I'm getting my coordinates
boxes = detections['detection_boxes'].numpy()[0]
# get all boxes from an array
max_boxes_to_draw = boxes.shape[0]
# get scores to get a threshold
scores = detections['detection_scores'].numpy()[0]
# this is set as a default but feel free to adjust it to your needs
min_score_thresh=.5
# # iterate over all objects found
coordinates = []
for i in range(min(max_boxes_to_draw, boxes.shape[0])):
    if scores[i] > min_score_thresh:
        class_id = int(detections['detection_classes'].numpy()[0][i] + 1)
        coordinates.append({
            "box": boxes[i],
            "class_name": category_index[class_id]["name"],
            "score": scores[i]
        })


print(coordinates)

Здесь каждый элемент (словарь) в списке координат представляет собой прямоугольник, который нужно нарисовать на изображении с координатами прямоугольников (нормализованными), именем класса и оценкой.

person Shreyas Vedpathak    schedule 14.07.2021