Объединить API обнаружения объектов TensorFlow с моделью Keras - PullRequest
0 голосов
/ 11 апреля 2020

Версия TensorFlow: 1.14 Python версия: 3.6.9

Моя цель - создать систему обнаружения объектов с классификацией. Я использовал Object Detection API и хочу передать выходные ограничивающие рамки в другие нейронные сети (есть 6 различных объектов для обнаружения, а затем я хочу классифицировать эти объекты с помощью нейронных сетей Keras по функциям объекта).

Когда Я использую Object Detection API только его ОК, но если я хочу использовать скрипт model.predict (), происходит сбой. Как я прочитал, есть проблема с графиком и сессиями.

Я довольно свободен sh ко всем этим вещам, поэтому я хочу спросить: возможно ли использовать несколько моделей одновременно?

Я читал о создании двух сессий и графиков, но ввод модели обнаружения объектов - это живое видео с веб-камеры, и я не хочу терять производительность сценария. Я пытался начать сеанс с каждым кадром, но это очень медленно.

Также, возможно, будет полезно обновить скрипт до Tensorflow 2.0?

РЕДАКТИРОВАТЬ:

Я хочу обнаружить фрукты и передать их другим моделям Keras, которые будут предсказывать их состояние. Обнаружение фруктов работает хорошо, но я не могу использовать дополнительную модель Keras из-за следующей ошибки:

Tensor Tensor("dense_3/Sigmoid:0", shape=(?, 1), dtype=float32) is not an element of this graph.

Предоставленный код:

import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf

import zipfile

from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image

from keras import models
from keras.preprocessing import image


import cv2
if 'cap' in globals():
      cap.release() 
cap = cv2.VideoCapture(0)

sys.path.append("..")

graph = tf.get_default_graph()

from utils import label_map_util
from utils import visualization_utils as vis_util

def limit(value, max_val, min_val):
    if(value > max_val):
        value = max_val
    elif(value < min_val):
        value = min_val      
    return value

# What model to download.
MODEL_NAME = 'inference_graph'
MODEL_FILE = MODEL_NAME + '.tar.gz'
DOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'

# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'

# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = 'training/labelmap.pbtxt'
NUM_CLASSES = 6

detection_graph = tf.Graph()
with detection_graph.as_default():
  od_graph_def = tf.GraphDef()
  with tf.gfile.GFile(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(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)

def load_image_into_numpy_array_updated(image):
  return np.array(image).astype(np.uint8)

# PATH_TO_TEST_IMAGES_DIR = 'test_images'
# TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 3) ]

# Size, in inches, of the output images.
IMAGE_SIZE = (12, 8)


# Loading a keras model
model = models.load_model('new_banana.h5')

with detection_graph.as_default():
    with tf.Session(graph=detection_graph) as sess:
        while True:
            ret, image_np = cap.read()
            # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
            image_np_expanded = np.expand_dims(image_np, axis=0)
            image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
            # Each box represents a part of the image where a particular object was detected.
            boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
            # Each score represent how level of confidence for each of the objects.
            # Score is shown on the result image, together with the class label.
            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')
            # Actual detection.
            (boxes, scores, classes, num_detections) = sess.run(
              [boxes, scores, classes, num_detections],
              feed_dict={image_tensor: image_np_expanded})

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

            # Code what are used to get thresholded bounding boxes from image
            # enlarge them about compenser value, limitates them
            # print them and send them to another script
            # 0 - apple, 2 - banana, 3 - orange, 4 - pear, 5 - pepper, 6 - tomato
            min_score_thresh = 0.7
            bboxes = boxes[scores > min_score_thresh]
            bclasses = classes[scores > min_score_thresh]

            image_np_new = cv2.resize(image_np_copy, (800,600))
            im_width, im_height = (800, 600)

            if bclasses.size > 0:
                final_box = []
                cropped_images = []
                compenser = 30
                if(bclasses[0] == 2): #if any of detected classes stands for 'banana'
                    for box in bboxes:
                        ymin, xmin, ymax, xmax = box
                        ymin0 = int(im_height * ymin) - compenser
                        ymax0 = int(im_height * ymax) + compenser
                        xmin0 = int(im_width * xmin) - compenser
                        xmax0 = int(im_width * xmax) + compenser

                        ymin1 = limit(ymin0, im_height, 0)
                        ymax1 = limit(ymax0, im_height, 0)
                        xmax1 = limit(xmax0, im_width, 0)
                        xmin1 = limit(xmin0, im_width, 0)

                        image_cropped = image_np_new[ymin1:ymax1, xmin1:xmax1]
                        height, width, _ = image_cropped.shape

                        if width > height:
                            image_cropped = cv2.resize(image_cropped, (200, 150))
                            image_cropped = cv2.rotate(image_cropped, cv2.ROTATE_90_CLOCKWISE)
                        else:
                            image_cropped = cv2.resize(image_cropped, (150, 200))

                        image_cropped = load_image_into_numpy_array_updated(image_cropped)
                        image_cropped = image_cropped.reshape((1,) + image_cropped.shape)
                        image_cropped = image_cropped/255
                        cropped_images.append(image_cropped)

                    if (len(cropped_images) > 0):
                        for image in cropped_images:
                            print(image.shape)
                            # input tensor 200, 150, 3
                            classes = model.predict_classes(image, batch_size=10)
                            print(classes)


            cv2.imshow('object detection', image_np)
            if cv2.waitKey(25) & 0xFF == ord('q'):
                cv2.destroyAllWindows()
                cap.release()
                break
...