TensorFlow / Python - сохранить результат / классификацию объекта как переменную и использовать его в имени файла - PullRequest
0 голосов
/ 14 января 2020

Я новичок в Python и TensorFlow и выполняю некоторое распознавание объектов с помощью API TensorFlow. Как только объект был идентифицирован, я хочу сохранить идентификационную метку как переменную, а затем использовать эту переменную в имени файла при сохранении классифицированного изображения с помощью cv2.imwrite (). Возможно ли это?

Вот код, с которым я сейчас работаю:

# Iterate through the files to be analysed in the directory
for filename in os.listdir(PATH_TO_DIR):
    if filename.lower().endswith(".jpg"):
        # Load image using OpenCV and
        # expand image dimensions to have shape: [1, None, None, 3]
        # i.e. a single-column array, where each item in the column has the pixel RGB value
        image = cv2.imread(filename)
        image = cv2.resize(image, (800,600))
        image_expanded = np.expand_dims(image, axis=0)
        # Perform the actual detection by running the model with the image as input
        (boxes, scores, classes, num) = sess.run(
            [detection_boxes, detection_scores, detection_classes, num_detections],
            feed_dict={image_tensor: image_expanded})
        # Draw the results of the detection (aka 'visulaize the results')
        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=4,
            min_score_thresh=0.60)
        # All the results have been drawn on image. Now display the image.
        cv2.imshow('Object detector', image)
        # Press any key to close the image
        cv2.waitKey(0)
        # Save the image
        cv2.imwrite(os.path.join(NEW_DIR_PATH, 'ID_'+filename), image)
        # Clean up
        cv2.destroyAllWindows()

Я немного модифицировал код с https://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10/blob/master/Object_detection_image.py

Я попытался добавить в

# Draw the results of the detection (aka 'visulaize the results')
        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=4,
            min_score_thresh=0.60)
        # Print name of identified class
        objects = []
        threshold = 0.6
        for index, value in enumerate(classes[0]):
            object_dict = {}
            if scores[0, index] > threshold:
                object_dict[(category_index.get(value)).get('name').encode('utf8')] = \
                                                                                    scores[0, index]
                objects.append(object_dict)
        print(objects)

Но это дает мне вывод [{b'Cat ': 0.99986553}]. Если возможно, я хочу, чтобы он просто напечатал 'Cat'

Заранее спасибо!

...