簡體   English   中英

Matplotlib 不會在 Jupyter Notebook 中顯示圖像

[英]Matplotlib will not show images in Jupyter Notebook

我正在使用 MatPlotLib 嘗試使用我在 TensorFlow 2.2.0 中訓練的模型顯示圖像中檢測到的對象。 我在 Jupyter Notebook 中使用 Python 3.8.3。 我有 10 張要顯示directory = 'images\\\\evaluation_images' (在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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM