<jupyter_start><jupyter_text>Object Detection From TF2 Saved Model This demo will take you through the steps of running an "out-of-the-box" TensorFlow 2 compatible detection model on a collection of images.
It is based on tutorial at https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/auto_examples/plot_object_detection_saved_model.htmlsphx-glr-auto-examples-plot-object-detection-saved-model-py

It is simpified to use a local model previously trained and exported with the `train_model.ipynb`-notebook.  Options  Test Images
Glob all files from a given directory.<jupyter_code>IMAGE_DIRECTORY = "test_images"
IMAGE_PATHS = [os.path.join(IMAGE_DIRECTORY, x) for x in os.listdir(IMAGE_DIRECTORY)]<jupyter_output><empty_output><jupyter_text>OR use some images from the training set...<jupyter_code>IMAGE_PATHS = ["DoorDetect-Dataset/images/0bf01ee25888cb45.jpg", "DoorDetect-Dataset/images/11739cf765a3f3d5.jpg"]<jupyter_output><empty_output><jupyter_text>Model and Labels<jupyter_code>PATH_TO_MODEL_DIR = "exported_models/ssd_mobilenet_v2_fpnlite_320x320"
PATH_TO_LABELS = "labelmap.pbtxt"<jupyter_output><empty_output><jupyter_text>Load the model
Next we load the exported model.<jupyter_code>import time
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as viz_utils

PATH_TO_SAVED_MODEL = PATH_TO_MODEL_DIR + "/saved_model"

print('Loading model...', end='')
start_time = time.time()

# Load saved model and build the detection function
detect_fn = tf.saved_model.load(PATH_TO_SAVED_MODEL)

end_time = time.time()
elapsed_time = end_time - start_time
print('Done! Took {} seconds'.format(elapsed_time))<jupyter_output><empty_output><jupyter_text>Load label map data (for plotting)
Label maps correspond index numbers to category names, so that when our convolution network
predicts `1`, we know that this corresponds to `door`.  Here we use internal utility
functions, but anything that returns a dictionary mapping integers to appropriate string labels
would be fine.<jupyter_code>category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS,
                                                                    use_display_name=True)<jupyter_output><empty_output><jupyter_text>Putting everything togetherThe code shown below loads an image, runs it through the detection model and visualizes thedetection results, including the keypoints.Note that this will take a long time (several minutes) the first time you run this code due totf.function's trace-compilation --- on subsequent runs (e.g. on new images), things will befaster.Here are some simple things to try out if you are curious:* Modify some of the input images and see if detection still works. Some simple things to try out here (just uncomment the relevant portions of code) include flipping the image horizontally, or converting to grayscale (note that we still expect the input image to have 3 channels).* Print out `detections['detection_boxes']` and try to match the box locations to the boxes in the image.  Notice that coordinates are given in normalized form (i.e., in the interval [0, 1]).* Set ``min_score_thresh`` to other values (between 0 and 1) to allow more detections in or to filter out more detections.<jupyter_code>%matplotlib inline
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings

def load_image_into_numpy_array(path):
    """Load an image from file into a numpy array.

    Puts image into numpy array to feed into tensorflow graph.
    Note that by convention we put it into a numpy array with shape
    (height, width, channels), where channels=3 for RGB.

    Args:
      path: the file path to the image

    Returns:
      uint8 numpy array with shape (img_height, img_width, 3)
    """
    return np.array(Image.open(path))


for image_path in IMAGE_PATHS:

    print('Running inference for {}... '.format(image_path), end='')

    image_np = load_image_into_numpy_array(image_path)

    # Things to try:
    # Flip horizontally
    # image_np = np.fliplr(image_np).copy()

    # Convert image to grayscale
    # image_np = np.tile(
    #     np.mean(image_np, 2, keepdims=True), (1, 1, 3)).astype(np.uint8)

    # The input needs to be a tensor, convert it using `tf.convert_to_tensor`.
    input_tensor = tf.convert_to_tensor(image_np)
    # The model expects a batch of images, so add an axis with `tf.newaxis`.
    input_tensor = input_tensor[tf.newaxis, ...]

    # input_tensor = np.expand_dims(image_np, 0)
    detections = detect_fn(input_tensor)

    # All outputs are batches tensors.
    # Convert to numpy arrays, and take index [0] to remove the batch dimension.
    # We're only interested in the first num_detections.
    num_detections = int(detections.pop('num_detections'))
    detections = {key: value[0, :num_detections].numpy()
                   for key, value in detections.items()}
    detections['num_detections'] = num_detections

    # detection_classes should be ints.
    detections['detection_classes'] = detections['detection_classes'].astype(np.int64)
    #print(detections)

    image_np_with_detections = image_np.copy()

    viz_utils.visualize_boxes_and_labels_on_image_array(
          image_np_with_detections,
          detections['detection_boxes'],
          detections['detection_classes'],
          detections['detection_scores'],
          category_index,
          use_normalized_coordinates=True,
          max_boxes_to_draw=200,
          min_score_thresh=.2,
          agnostic_mode=False)

    plt.figure()
    plt.imshow(image_np_with_detections)
    print('Done')
plt.show()

# sphinx_gallery_thumbnail_number = 2<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.07928692699490662, 'fraction_numerical': 0.009168081494057725, 'mean_word_length': 4.056652360515021, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 25, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '29537', 'license': 'MIT', 'n_tokens_mistral': 1884, 'n_tokens_neox': 1742, 'n_words': 541, 'path': 'test_model.ipynb', 'repo_name': 'Aachen-Armchair-Engineers/model', 'size': '5890'}