简体   繁体   English

Matplotlib 不会在 Jupyter Notebook 中显示图像

[英]Matplotlib will not show images in Jupyter Notebook

I am using MatPlotLib to try display objects detected in images using a model that I trained in TensorFlow 2.2.0.我正在使用 MatPlotLib 尝试使用我在 TensorFlow 2.2.0 中训练的模型显示图像中检测到的对象。 I am using Python 3.8.3 in Jupyter Notebook.我在 Jupyter Notebook 中使用 Python 3.8.3。 I have 10 images that I am trying to display (defined in the directory = 'images\\\\evaluation_images' line of code).我有 10 张要显示directory = 'images\\\\evaluation_images' (在directory = 'images\\\\evaluation_images'代码行中定义)。 Below is the python script as well as the corresponding output:下面是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

THis means that the script ran correctly, but I need to see something like this:这意味着脚本运行正确,但我需要看到如下内容: 在此处输入图片说明

How can I display the output?如何显示输出?

您是否尝试过添加%matplotlib inline

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM