API обнаружения объектов Tensorflow - получить координаты ящиков - PullRequest
1 голос
/ 11 марта 2020
detection_graph = tf.Graph()
with detection_graph.as_default():
    od_graph_def = tf.GraphDef()
    with tf.gfile.GFile(MODEL_PATH, 'rb') as fid:
        serialized_graph = fid.read()
        od_graph_def.ParseFromString(serialized_graph)
        tf.import_graph_def(od_graph_def, name='')

    sess = tf.Session(graph=detection_graph)

image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
num_detections = detection_graph.get_tensor_by_name('num_detections:0')

gameWindow = [0, 0, 200, 300]

while True:
    image = np.array(ImageGrab.grab(bbox=(gameWindow[0], gameWindow[1], gameWindow[2], gameWindow[3])))
    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    image_expanded = np.expand_dims(image_rgb, axis=0)

    (boxes, scores, classes, num) = sess.run(
        [detection_boxes, detection_scores, detection_classes, num_detections],
        feed_dict={image_tensor: image_expanded})

    vis_util.visualize_boxes_and_labels_on_image_array(
        image,
        np.squeeze(boxes),
        np.squeeze(classes).astype(np.int32),
        np.squeeze(scores),
        category_index,
        use_normalized_coordinates=True,
        line_thickness=8,
        min_score_thresh=0.60)

    frame = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    # print("Made it ")
    cv2.imshow('Detect the dumb trees', frame)

    if cv2.waitKey(1) == 27:
        break
cv2.destroyAllWindows()

Я пытаюсь получить x1, y1, x2, y2 координаты ящиков, которые API dr aws использует vis_util.visualize_boxes_and_labels_on_image_array()

Я пытался просмотреть detection_boxes, но я получаю куча ценностей, о которых я понятия не имею, что они имеют в виду.

Может кто-нибудь предложить мне решение, пожалуйста? Спасибо

Ответы [ 2 ]

0 голосов
/ 11 марта 2020

Этот вопрос похож на ваш: Как найти координаты ограничительных рамок в API обнаружения объектов Tensorflow

И кто-то опубликовал простое решение для кода.

Существует другой способ, где вы можете манипулировать функцией visualize_boxes_and_labels_on_image_array (), чтобы вернуть координаты Что-то вроде:

coordinates_list = []
for box, color in box_to_color_map.items():
  ymin, xmin, ymax, xmax = box
  height, width, channels = image.shape
  ymin = int(ymin*height)
  ymax = int(ymax*height)
  xmin = int(xmin*width)
  xmax = int(xmax*width)
  coordinates_list.append([xmin, ymin, xmax, ymax])

return coordinates_list
0 голосов
/ 11 марта 2020

Числа в Detection_boxes - [ymin, xmin, ymax, xmax], и они нормализованы к размеру вашего изображения, так как «use_normalized_coordinates = True» в вашем скрипте. Каждый индекс в определении_боксов соответствует одному и тому же индексу в обнаружениях и классах обнаружения. Таким образом, вы должны найти, какой объект вы хотите получить, с каким пороговым значением, чтобы получить индекс для обнаружения_поиска. Пример:

boxes=[]
    for i in range(len(detection_boxes)):
        if detection_classes[i]=3 and detection_scores[i]>0.9:
             boxes.append(detection_boxes[i])

Порог оценки, установленный здесь, равен 0,9, а класс, который я ищу, равен 3. Эти совпадающие блоки хранятся в полях вызова массива.

...