I write a dog-classifier in a Jupyter notebook that, every time a dog is detected in an image, should show the image and print some text describing it. Somehow, the images are always displayed after all the text was printed, no matter in which order I put plt.imshow()
and print()
. Does anybody know why this is the case?
Thank you!
Here is my code-snippet:
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")
The output is like this:
It seems you are using Juypter notebook. This always shows any autogenerated output (like the matplotlib figures) last in the output.
You may use IPython.display.display
to display the figures at the position of the output where they belong.
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()
Output:
I tried this in my ipython notebook, if I first call plt.imshow(img) and plt.show() right after I get the image first and the text after.
来源:https://stackoverflow.com/questions/49365763/matplotlib-sequence-is-off-when-using-plt-imshow