python - Matplotlib 不会在 Jupyter Notebook 中显示图像
问题描述
我正在使用 MatPlotLib 尝试使用我在 TensorFlow 2.2.0 中训练的模型显示在图像中检测到的对象。我在 Jupyter Notebook 中使用 Python 3.8.3。我有 10 张图像要显示(在directory = 'images\\evaluation_images'
代码行中定义)。以下是 python 脚本以及相应的输出:
#Import modules
import time
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Suppress TensorFlow logging (1)
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as viz_utils
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore') # Suppress Matplotlib warnings
tf.get_logger().setLevel('ERROR') # Suppress TensorFlow logging (2)
# Enable GPU dynamic memory allocation
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
#Specify directory where trained model is saved
PATH_TO_SAVED_MODEL = 'exported-models\\my_model\\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))
#Path to .pbtxt file
category_index = label_map_util.create_category_index_from_labelmap('annotations\\label_map.pbtxt',use_display_name=True)
#Detect objects in images
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))
#Specify path for test images
directory = 'images\\evaluation_images'
IMAGE_PATHS = [directory + "\\" + f for f in os.listdir(directory) if f[-4:] in ['.jpg','.png','.bmp']]
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)
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=.30,
agnostic_mode=False)
plt.figure()
plt.imshow(image_np_with_detections)
print('Done')
plt.show()
# sphinx_gallery_thumbnail_number = 2
Loading model...Done! Took 37.69696593284607 seconds
Running inference for images\evaluation_images\weed7614.png... Done
Running inference for images\evaluation_images\weed7629.png... Done
Running inference for images\evaluation_images\weed7660.png... Done
Running inference for images\evaluation_images\weed7676.png... Done
Running inference for images\evaluation_images\weed7692.png... Done
Running inference for images\evaluation_images\weed7725.png... Done
Running inference for images\evaluation_images\weed7740.png... Done
Running inference for images\evaluation_images\weed7755.png... Done
Running inference for images\evaluation_images\weed7771.png... Done
Running inference for images\evaluation_images\weed7788.png... Done
如何显示输出?
解决方案
你试过添加%matplotlib inline
吗?
推荐阅读
- typo3 - TYPO3 DataHandler: PHP-programmatically get some ContentElement's translate ContentElement UID
- python - 无法建立新连接:[Errno 111] Connection refused'))
- node.js - Ramda 中 Lodash _.transform 的等价物是什么?
- c++ - 将具有相反操作数的两个函数重构为一个
- javascript - 我可以使用 javascript 或 jquery 以及从 MVC 中的 razor 生成的动态单选按钮吗
- angular - 如何在 Angular 8 中降低 Material datepicker 日历的宽度和高度?
- c# - Boostrap 4 模式中的输入元素不是 Asp.Net 形式的回发
- ffmpeg - 为什么 ffmpeg 需要 DNS 解析器作为其依赖项?
- sql - Oracle SQL 会话的生命周期是什么?
- html - 我如何将其居中