Matplotlib - 使用 plt.imshow() 时序列关闭

Matplotlib - sequence is off when using plt.imshow()

我在 Jupyter notebook 中编写了一个狗分类器,每次在图像中检测到狗时,都应该显示该图像并打印一些描述它的文本。不知何故,无论我按什么顺序放置 plt.imshow()print(),图像总是在所有文本打印后显示。有人知道为什么会这样吗?

谢谢!

这是我的代码片段:

for i in range (0, 1,1):

    all_counter+=1

    if dog_detector(dog_files_short[i]):

        img = image.load_img(dog_files_short[i], target_size=(224, 224))
        plt.show()
        plt.imshow(img)
        time.sleep(5)
        print("That's a dog!!!!")
        dog_counter+=1
        print("______________")

    else: 

        print("______________")
        img = image.load_img(dog_files_short[i], target_size=(224, 224))
        plt.show()
        plt.imshow(img)
        print("No Doggo up here :(")
        print(ResNet50_predict_labels(dog_files_short[i]))
        print("______________")

print((dog_counter/all_counter)*100, "% of the dog pictures are classified as dogs")

输出是这样的:

我在我的 ipython 笔记本中试过这个,如果我先调用 plt.imshow(img) 和 plt.show() ,然后我先获取图像,然后获取文本。

看来您使用的是 Juypter notebook。这始终在输出的最后显示任何自动生成的输出(如 matplotlib 图形)。

您可以使用IPython.display.display在它们所属的输出位置显示数字。

import matplotlib.pyplot as plt
import numpy as np
from IPython.display import display

images = [np.random.rayleigh((i+1)/8., size=(180, 200, 3)) for i in range(4)]

dog_detector = lambda x: np.random.choice([True,False])
dog_counter = 0

for i in range(len(images)):

    if dog_detector(images[i]):
        dog_counter+=1
        fig, ax = plt.subplots(figsize=(3,2))
        ax.imshow(images[i])
        display(fig)
        display("That's a dog!!!!")
        display("______________")

    else: 

        display("______________")
        fig, ax = plt.subplots(figsize=(3,2))
        ax.imshow(images[i])
        display(fig)
        display("No Doggo up here :(")
        display("______________")

perc = (dog_counter/float(len(images)))*100 
display("{}% of the dog pictures are classified as dogs".format(perc))
plt.close()

输出: