Python 2.7 GUI with Matplotlib Issue - python

I am building a GUI that is a heads-up display and in the background an animation is played.
The tool is supposed to read data from a text file that contains the information that will be displayed. Also, the animation is a library of images. Thus, each second the code looks at a line in the table and displays the information for that row as well as the image associated with that row.
I have implemented a possible solution to this particular need using Matplotlib. My issue is that once the code is ran, if I click anywhere on the screen, or try to open a new window while the loop is running, I get a "(Not Responding") status on the program toolbar
Figure 1 - Not Responding
How can I prevent this issue from happening?
Or are there better ways to implement this functionality? I has to be able to read a txt/csv file as well as render the images one after the other.
Here is a sample of the code:
import matplotlib.pyplot as plt
import numpy as np
import time
from scipy.misc import imread
import matplotlib.cbook as cbook
import pandas as pd
from pylab import *
#Open file with information for HUD
filename = "data.txt"
rndz_data = pd.read_table(filename, sep="\s+")
frames = np.arange(5)
plt.ion()
fig = plt.figure()
#Create array of image files
datafile = [cbook.get_sample_data('rndz0000.png'),
cbook.get_sample_data('rndz0001.png'),
cbook.get_sample_data('rndz0002.png'),
cbook.get_sample_data('rndz0003.png'),
cbook.get_sample_data('rndz0004.png')]
#Create plot and animate
for i in frames:
img = imread(datafile[i])
plt.clf()
plt.imshow(img, zorder=0, extent=[0.5, 8.0, 1.0, 7.0])
plt.plot
plt.draw()
time.sleep(1)

Related

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

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.
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:

How to show single colorbar in loop by Python?

I've tried to plot images of my loaded 2D data (512x512 pixels) in a loop by matplotlib with Python3. But it turns out to show weird images with multiple colorbars. Here is my code:
import numpy as np
import sys
import os
from load_images import load, File
import matplotlib.pyplot as plt
from matplotlib import cm
arr_spe = [x for x in os.listdir() if x.endswith(".SPE")]
for x in arr_spe:
try:
dat = load(x)
plt.imshow(dat,cmap=cm.jet, vmax = 2000)
plt.colorbar()
plt.savefig(x[:-4]+'.png', dpi=500, bbox_inches='tight')
except ValueError as error:
print('ValueError(empty)-'+x)
I use the code to load my data in the following link: Reading SPE file from CCD camera by naming the code as load_images.py.
And I got many images like
Does anybody have ideas to solve this issue? Just simply show single colorbar in an image

How do you log stretch a FITS image and change its contrast?

I'm trying to use astropy 2.0.11 with python 2.7.15 to edit a fits image by applying a log stretch to it and change the contrast, and I have't been able to figure it out.
I've been trying to follow the tutorials on the astropy website for opening and manipulating fits files, but I'm wondering if the tutorials will only work for the latest version of astropy and on python 3?
Sorry about the organization of my code. This is prototype code and I'm just trying to test a few things and get this to work.
import time
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
import astropy.visualization
from astropy.io import fits
from astropy.utils.data import download_file
from astropy.visualization import astropy_mpl_style
plt.style.use(astropy_mpl_style)
from astropy.utils.data import get_pkg_data_filename
def main():
#My own fits file
#fitsImage = get_pkg_data_filename("C:\\20180807T000456.fits")
fitsImage = download_file('http://data.astropy.org/tutorials/FITS-images/HorseHead.fits', cache=True )
hdu_list = fits.open(fitsImage)
hdu_list.info()
#norm = ImageNormalize(stretch=LogStretch())
image_data = fits.getdata(fitsImage)
print(type(image_data))
print(image_data.shape)
hdu_list.close()
plt.figure()
plt.imshow(image_data, cmap='gray', norm=LogNorm())
plt.colorbar()
# I chose the tick marks based on the histogram above
cbar = plt.colorbar(ticks=[5.e3,1.e4,2.e4])
cbar.ax.set_yticklabels(['5,000','10,000','20,000'])
time.sleep(10)
I am also unable to get the image to display with the plt.imshow()
Any insight would be helpful
You're so close! I ran your code in Python 2.7 and all you need to do is add
plt.show()
before time.sleep(10) (any reason you're including this?) and you get
Also, I don't think you need to include the colorbar and yticklabels, plt.imshow automatically adds the colorbar with the lognorm scale (I commented that section out when I got the image).

How to correctly combine PNG and FITS data into one Matplotlib figure in Python?

I have a FITS file of 4545x4545 pixels with a header containing its coordinate system. Since DS9 (another software to view and handle FITS images) handles the color map scaling better, I had the idea of:
open the FITS file using DS9 to tweak the color map of the image,
save this image in a PNG file,
load this PNG file in matplotlib and add the header from the original FITS file, so I can add the coordinate system to the PNG file.
But the coordinates are not showing correctly, because the pixelization changes to different values in every step. How can I do this correctly?
This the relevant part of my code:
from astropy.io import fits
import matplotlib.pyplot as plt
import aplpy
from wcsaxes import WCSAxes
from astropy import wcs
import sys
import matplotlib.image as mpimg
image_fits = 'image_in.fits'
image_png = 'image_in.png' # this came from the one before, has different pixelization
image_data_png = mpimg.imread(image_png)
image_head_fits = fits.getheader(image_fits)
hdu_list = fits.open(image_fits)
F = aplpy.FITSFigure(hdu_list, figure=plt.figure(1))
fig = plt.figure()
mywcs = wcs.WCS(image_head_fits)
ax = WCSAxes(fig,[0.1, 0.1, 0.8, 0.8],wcs=mywcs)
fig.add_axes(ax)
ax.imshow(image_data_png)
plt.savefig('image_out.png')

Ploting and labeling data with variables matplotlib

I've been collecting data from experiments and dumping them into .txt files and I decided to try and write a quick script to plot them with matplotlib. The plotting works fine, but I do not know how to label the plot based on the file name.
from numpy import *
from pylab import *
from matplotlib import rc
import sys
import os
rc('text',usetex=True)
rc('font',**{'family':'serif','serif':['Computer Modern']})
os.chdir(".")
for files in os.listdir("."):
if files.endswith(".txt"):
f = open(files,'r')
temp = []
for l in f:
temp.append(float(l))
plot(temp,labels=files)
hold(True)
legend(loc='lower left')
hold(False)
# Save the figure in a separate file
savefig('test.png')
# Draw the plot to the screen
show()
The problem seems to be with plot(temp,lables=files). If I put lables=files I get the error TypeError: There is no line property "labels". If I try and put labels='files', all the plots are labelled files which is useless. Does anyone know how to assign a lable to a plot based on a variable?
You want to use label, not lables or labels.
plot(temp,label = files)

Categories