Как мне распечатать (номер кадра, информацию об ограничивающей рамке, достоверность) обнаруженных объектов в текстовый файл в детекторе объектов tenorflow?

Я использовал api обнаружения объектов tensorflow для обнаружения нескольких объектов в моих видео. Однако я изо всех сил пытался выяснить, как записать эти результирующие обнаружения объектов в текстовый / CSV / xml-файл (в основном информация об ограничивающей рамке, номер кадра последовательности изображений, надежность bbox)

Я видел несколько ответов в stackoverflow и github, но большинство из них были либо расплывчатыми, либо я просто не мог получить точный ответ, который ищу.

Ниже показана последняя часть кода обнаружения, я знаю, что обнаружение_boxes и обнаружение_scores - это то, что мне нужно, но я просто не могу понять, как записать их в текстовый файл, а также записать только окончательные обнаружения bbox, которые видны на изображениях. но не ВСЕ ограничивающие рамки обнаружения

for image_path in TEST_IMAGE_PATHS:   
    image = Image.open(image_path) # the array based representation of the image will be used later in order to prepare the result image with boxes and labels on it.
    image_np = load_image_into_numpy_array(image)  # Expand dimensions since the model expects images to have shape: [1, None, None, 3]   
    image_np_expanded = np.expand_dims(image_np, axis=0)  # Actual detection.
    output_dict = run_inference_for_single_image(image_np_expanded, detection_graph) # 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)

person anzy0621    schedule 10.07.2019    source источник


Ответы (1)


Вы можете попробовать следующий код

image = Image.open(image_path)
# the array based representation of the image will be used later in order to prepare the
# result image with boxes and labels on it.
image_np = load_image_into_numpy_array(image)  
# Expand dimensions since the model expects images to have shape: [1, None, None, 3]
image_np_expanded = np.expand_dims(image_np, axis=0)

boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
scores = detection_graph.get_tensor_by_name('detection_scores:0')
classes = detection_graph.get_tensor_by_name('detection_classes:0')
num_detections = detection_graph.get_tensor_by_name('num_detections:0')    

(boxes, scores, classes, num_detections) = sess.run(
          [boxes, scores, classes, num_detections],
          feed_dict={image_tensor: image_np_expanded})

width = 1024
height = 600
threshold = 0.5

temp = [] # list to store scores greater than 0.5

# iterate through all scores and pick those having a score greater than 0.5

for index,value in enumerate(classes[0]):
    if scores[0,index] > threshold:      
        temp.append(scores[0,index])

# Similarly, classes[0,index] will give you the class of the bounding box detection

# Actual detection.
output_dict = run_inference_for_single_image(image_np, detection_graph)

# For printing the bounding box coordinates
for i,j in zip(output_dict['detection_boxes'],output_dict['detection_scores']):
        if(j>threshold):
            print(i[1]*width,i[0]*height,i[3]*width,i[2]*height)

Приведенный выше фрагмент кода предоставит вам координаты ограничивающей рамки и оценки обнаружения. Вы можете использовать минимальный порог для фильтрации ненужных обнаружений. Я надеюсь, что это помогает вам. Кроме того, я не совсем понял, что вы имели в виду под frame number. Не могли бы вы пояснить, что вы на самом деле имеете в виду.

Пожалуйста, дайте мне знать, если у вас возникнут проблемы

person Jitesh Malipeddi    schedule 30.07.2019