How do I clear images and data from previous runs in Python? - python

Disclaimer: I am new to Python and I have the latest Anaconda-Python (3.8.3) installed in my computer. My code is
if __name__ == '__main__':
import imageio
import matplotlib.pyplot as plt
plt.clf()
pic = imageio.imread('Photo_Vikash_pandey.jpg')
plt.figure(figsize = (15,15))
plt.imshow(pic)
Every time I run the code I see images piled up in the adjoining window of Spyder IDE. I want that every time I run the code, it has no history of its previous execution. I do not wish to see image display from previous runs of the code.

Related

Matplotlib not showing plot when program is executed in the VS Code terminal

I have this simple program here
import numpy as np
import matplotlib.pyplot as plt
num_of_intervals = 2000
x = np.linspace(-10,10,num=num_of_intervals)
y_inputs = 1/(1+np.exp(-x)) # SIGMOID FUNCTION
plt.figure(figsize = (15,9))
plt.plot(x,y_inputs,label = 'Sigmoid Function')
plt.vlines(x=0, ymin = min(y_inputs), ymax=max(y_inputs), linestyles='dashed')
plt.title('Sigmoid Function')
plt.show()
When the above program is ran in the vscode terminal. The plot cannot be seen (usually a pop-up window appears showing the plot).
But when the program is ran in the Ubuntu terminal, the plot can be seen as a pop-up window.
Any idea how I can solve this issue with vscode.
OS : Ubuntu 20.04
Visual Studio Code 1.54.3
Python : 3.8.5
Double check that this option is turned on in Settings: terminal.integrated.inheritEnv

python Ginput working in spyder but not working from terminal or command window

I have a program to scatter plot eigenvalues and from the user click to retrieve the selected number/coordinate and use that input for further analysis. The program is working fine in Spyder console ( I am using python 2.7.16 and matplotlib 2.2.3). But when I execute the same code from the mac terminal, it is showing the plot but not recognizing the user click. (I have checked the same code from windows command terminal and it is also not working there even though it is working in spyder installed in my windows system). The program is also not showing any error. A sample program is provided here for reference.
import matplotlib.pyplot as plt
import numpy as np
n = 10
real_part = np.random.normal(size=n)
imag_part = np.random.normal(size=n)
z = np.array(real_part, dtype=complex)
z.imag = imag_part
fig,ax = plt.subplots(figsize=(8,5))
ax.scatter(z.real,z.imag,marker='x',color='r')
plt.grid(which='both',axis='both')
plt.title('Complex plot')
plt.show()
userInput=plt.ginput(n=1, timeout=30, show_clicks=True)
print("User Input is %s"%userInput)
Any help on this would be highly appreciated.
Thanks in advance.

animating image stack with vispy

I'm trying to migrate from MATLAB to Python and one of the things I frequently rely on during development in Matlab is the ability to rapidly visualize slices of a datacube by looping through layers and calling drawnow, e.g.
tst = randn(1000,1000,100);
for n = 1:size(tst, 3)
imagesc(tst(:,:,n));
drawnow;
end
When I tic/toc this in MATLAB it shows that the figure is updating at about 28fps. In contrast, when I try to do this using matplotlib's imshow() command this runs at a snails pace in comparison, even using set_data().
import matplotlib as mp
import matplotlib.pyplot as plt
import numpy as np
tmp = np.random.random((1000,1000,100))
myfig = plt.imshow(tmp[:,:,i], aspect='auto')
for i in np.arange(0,tmp.shape[2]):
myfig.set_data(tmp[:,:,i])
mp.pyplot.title(str(i))
mp.pyplot.pause(0.001)
On my computer this runs at about 16fps with the default (very small) scale, and if I resize it to be larger and the same size as the matlab figure it slows down to about 5 fps. From some older threads I saw a suggestion to use glumpy and I installed this along with all of the appropriate packages and libraries (glfw, etc.), and the package itself works fine but it no longer supports the easy image visualization that was suggested in a previous thread.
I then downloaded vispy, and I can make an image with it using code from this thread as a template:
import sys
from vispy import scene
from vispy import app
import numpy as np
canvas = scene.SceneCanvas(keys='interactive')
canvas.size = 800, 600
canvas.show()
# Set up a viewbox to display the image with interactive pan/zoom
view = canvas.central_widget.add_view()
# Create the image
img_data = np.random.random((800,800, 3))
image = scene.visuals.Image(img_data, parent=view.scene)
view.camera.set_range()
# unsuccessfully tacked on the end to see if I can modify the figure.
# Does nothing.
img_data_new = np.zeros((800,800, 3))
image = scene.visuals.Image(img_data_new, parent=view.scene)
view.camera.set_range()
Vispy seems very fast and this looks like it will get me there, but how do you update the canvas with new data? Thank you,
See ImageVisual.set_data method
# Create the image
img_data = np.random.random((800,800, 3))
image = scene.visuals.Image(img_data, parent=view.scene)
view.camera.set_range()
# Generate new data :
img_data_new = np.zeros((800,800, 3))
img_data_new[400:, 400:, 0] = 1. # red square
image.set_data(img_data_new)

Animation freezes after a number of frames after upgrading Matplotlib

I recently updated my matplotlib python package to version 2.2.0, and now some previously working code to save an animation does not work. Instead of saving an animation, the code freezes at a certain iteration number. It becomes unresponsive to interrupts and throws a PyEval_RestoreThread fatal error when I manage to close the command window.
I am using Enthought Canopy. The code still works as normal with other versions of python and matplotlib.
I can replicate the problem with this:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
SIZE = 128
fig, ax = plt.subplots()
ims = ax.imshow(np.random.rand(SIZE, SIZE))
i = 0
def update_animation(*args):
global i
i = i + 1
image = np.random.rand(SIZE, SIZE)
ims.set_data(image)
print "Iteration "+str(i)
F_NAME = "anim_test.mp4"
NUM_ITERS = 1000
FFwriter = animation.FFMpegWriter(fps=6, bitrate=500)
anim=animation.FuncAnimation(fig,update_animation,frames=NUM_ITERS,blit=False, repeat=False, interval=200)
anim.save(F_NAME, writer=FFwriter)
print "saved animation to " + F_NAME
Changing the bitrate parameter changed the number of the frame the program halts at. For bitrate=500, it halts around frame 46.
How can I stop pyplot freezing before all frames can be saved?
EDIT
My system details:
Python 2.7.6 64bit Enthought Canopy
Windows 8
8GB RAM
ffmpeg version N-79075-ga7b8a6e

Stop python GUI program from exiting when run from CLI

How can easily I make a blocking GUI app on OS X?
I have a simple python plotting program. When I run it from inside an existing python interactive session, or from within iPython, the GUI window is displayed, and I can see it and interact with it. When I run the .py file from the CLI, the GUI flashes and closes immediately.
I would like to run this from the command line and have the GUI remain.
if __name__ == "__main__":
import matplotlib
from matplotlib import pyplot
data = range(1,10)
fig = pyplot.plot(data)
pyplot.show()
It sounds as though interactive mode has been enabled somehow, although I'm not sure where. Try it like this:
def main():
import matplotlib.pyplot as plt
data = range(1,10)
fig = plt.plot(data)
plt.ioff() # turns interactive mode OFF, should make show() blocking
plt.show()
if __name__ == "__main__":
main()

Categories