Skip to content

Instantly share code, notes, and snippets.

@afaqueumer
Created January 8, 2023 18:32
Show Gist options
  • Save afaqueumer/bd98d411c9bc5f026b31db22580a9f6f to your computer and use it in GitHub Desktop.
Save afaqueumer/bd98d411c9bc5f026b31db22580a9f6f to your computer and use it in GitHub Desktop.
# Import the required libraries
import time
import numpy as np
from PIL import Image
from matplotlib import pyplot as plt
%matplotlib inline
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as viz_utils
import tensorflow as tf
import numpy as np
%matplotlib inline
# Define the paths
testing_image_path = os.path.join('Tensorflow' , 'workspace', 'images', 'batman', 'jj.jpg')
model_dir = paths["checkpoint_path"]
labels_path = files["labelmap"]
saved_model_path = os.path.join(model_dir ,"export" , "saved_model")
# Load exported model
print('Loading model...', end='')
start_time = time.time()
detect_fn = tf.saved_model.load(saved_model_path)
end_time = time.time()
elapsed_time = end_time - start_time
print('Done! Took {} seconds'.format(elapsed_time))
# Begin Detection
category_index = label_map_util.create_category_index_from_labelmap(labels_path, use_display_name=True)
image_np = np.array(Image.open(testing_image_path))
input_tensor = tf.convert_to_tensor(image_np)
input_tensor = input_tensor[tf.newaxis, ...]
detections = detect_fn(input_tensor)
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
detections['detection_classes'] = detections['detection_classes'].astype(np.int64)
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=1,
min_score_thresh=.2,
agnostic_mode=False)
# Display the image with detected box
plt.imshow(image_np_with_detections)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment