display images inside a loop by overwriting the existing plot/figure in python

Viewed 1330

I have hundreds of thousands of images which I have to get from URL, see them ,tag them and then save them in their respective category as spam or non spam. On top of that, I'll be working with google which makes it impossible. My idea is that instead of looking at each image by opening, analysing, renaming and then saving them in directory, I just get the image from url, see within a loop, input a single word and based on that input, my function will save them in their respective directories.

I tried doing

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

fg = plt.figure()
for i in range(5):
  plt.imshow(np.random.rand(50,50))
  plt.show()
  x = input()
  print(x)

but instead of overwriting the existing frame, it is plotting a different figure. I have even used 1,1 subplot inside a loop but it is not working. Ipython's method does not even display inside a loop either. Could somebody please help me with this problem.

1 Answers

You can make use of matplotlib's interactive mode by invoking plt.ion(). An example:

import numpy as np
import matplotlib.pyplot as plt
%matplotlib notebook
fig, ax = plt.subplots()

plt.ion()
plt.show()
for i in range(5): 
    ax.imshow(np.random.rand(50,50))  # plot the figure
    plt.gcf().canvas.draw()
    yorn = input("Press 1 to continue, 0 to break") 
    if yorn==0:
        break

Expected output:

enter image description here

Related