Save wfdb output as an image - python

I am trying to plot ECG signals using wfbd package
It is working but I can't save the output in an image file.
here is the code I am using:
record = wfdb.rdrecord('ptb/records100/00000/00001_lr')
wfdb.plot_wfdb(record=record, title='ECG', figsize=(20,20))
fig1=plt.figure()
fig1.savefig('test.png', dpi=100)
the image saved is always empty
anyone suggestions ?

What you want to do is save the figure object that wfdb plotted the signal to.
However, you're creating a new figure and saving it.
wfdb.plot_wfdb has a return_fig argument to get the figure object you want.
Call savefig on that object.
Doc here
fig = wfdb.plot_wfdb(..., return_fig=True)
fig.savefig("test.png")

Related

Image not updating in python plot during animation

The Problem:
I'm trying to simulate a live video by cycling through a series of still images I have saved in a directory, but when I add the animation and update functions my plot is displayed empty.
Background on why I'm doing this:
I believe its important for me to do it this way rather than a complete change of approach, say turning the images into a video first then displaying that, because what I really want to test is the image analysis I will be adding and then overlaying on each frame. The final application will be receiving frames one by one from a camera and will need to do some processing, display the image + annotations + output the data as .csv etc... I'm simulating this for now because I do not have any of the hardware to generate the images and will not have it for several months during which time I need to get the image processing set up, but I do have access to some sets of stills that are approximately what will be produced. In case its relevant my simulation images are 1680x1220 and are 1.88 Mb TIFFs, though I could covert and compress them if needed, and in the final form the resolution will be a bit higher and probably the image format could be adjusted if needed.
What I have tried:
I followed an example to list all files in a folder, and an example
to update a plot. However, the plot displays blank when I run the
code.
I added a line to print the current file name, and I can see this
cycling as expected.
I also made sure the images will display in the plot if I just create
a plot and add one image, and they do. But, when combined with the
animation function the plot is blank and I'm not sure what I've done
wrong/failed to include.
I also tried adding a plt.pause() in the update, but again this
didn't work.
I increased the interval up to 2000 to give it more time, but that didn't work. I believe 2000 is extreme, I'm expecting it should work with more like 20-30fps. Going to 0.5fps tells me the code is wrong or incomplete, rather than it just being a question of needing time to read the image file.
I appreciate no one else has my images, but they are nothing special. I'm using 60 images but I guess it could be tested with any 2 random images and setting range(60) to range(2) instead?
The example I copied originally demonstrated the animation function by making a random array, and if I do that it will show a plot that updates with random squares as expected.
Replacing:
A = np.random.randn(10,10)
im.set_array(A)
...with my image instead...
im = cv2.imread(files[i],0)
...and the plot remains empty/blank. I get a window shown called "Figure1" (like when using the random array), but unlike with the array there is nothing in this window.
Full code:
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import os
import cv2
def update(i):
im = cv2.imread(files[i],0)
print(files[i])
#plt.pause(0.1)
return im
path = 'C:\\Test Images\\'
files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
for file in f:
if '.TIFF' in file:
files.append(os.path.join(r, file))
ani = FuncAnimation(plt.gcf(), update, frames=range(60), interval=50, blit=False)
plt.show()
I'm a python and a programming novice so have relied on adjusting examples others have given online but I have only a simplistic understanding of how they are working and end up with a lot of trial and error on the syntax. I just can't figure out anything to make this one work though.
Cheers for any help!
The main reason nothing is showing up is because you never add the images to the plot. I've provided some code below to do what you want, be sure to look up anything you are curious about or don't understand!
import glob
import os
from matplotlib import animation
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
IMG_DIRPATH = 'C:\\Test Images\\' # the folder with your images (be careful about
# putting spaces in directory names!)
IMG_EXT = '.TIFF' # the file extension of your images
# Create a figure, and set to the desired size.
fig = plt.figure(figsize=[5, 5])
# Create axes for the current figure so that images can be sized appropriately.
# Passing in [0, 0, 1, 1] makes the axes fill the whole figure.
# frame_on=False means we won't have a bounding box, and setting xticks=[] and
# yticks=[] means that we won't have pesky tick marks along our image.
ax_props = {'frame_on': False, 'xticks': [], 'yticks': []}
ax = plt.axes([0, 0, 1, 1], **ax_props)
# Get all image filenames.
img_filepaths = glob.glob(os.path.join(IMG_DIRPATH, '*' + IMG_EXT))
def update_image(img_filepath):
# Remove all existing images on the axes, and restore our settings.
ax.clear()
ax.update(ax_props)
# Read the current image.
img = mpimg.imread(img_filepath)
# Add the current image to the plot axes.
ax.imshow(img)
anim = animation.FuncAnimation(fig, update_image, frames=img_filepaths, interval=250)
plt.show()

Plot all the graph and save it in pdf file in python [duplicate]

In python (for one figure created in a GUI) I was able to save the figure under .jpg and also .pdf by either using:
plt.savefig(filename1 + '.pdf')
or
plt.savefig(filename1 + '.jpg')
Using one file I would like to save multiple figures in either .pdf or .jpg (just like its done in math lab). Can anybody please help with this?
Use PdfPages to solve your problem. Pass your figure object to the savefig method.
For example, if you have a whole pile of figure objects open and you want to save them into a multi-page PDF, you might do:
import matplotlib.backends.backend_pdf
pdf = matplotlib.backends.backend_pdf.PdfPages("output.pdf")
for fig in xrange(1, figure().number): ## will open an empty extra figure :(
pdf.savefig( fig )
pdf.close()
Do you mean save multiple figures into one file, or save multiple figures using one script?
Here's how you can save two different figures using one script.
>>> from matplotlib import pyplot as plt
>>> fig1 = plt.figure()
>>> plt.plot(range(10))
[<matplotlib.lines.Line2D object at 0x10261bd90>]
>>> fig2 = plt.figure()
>>> plt.plot(range(10,20))
[<matplotlib.lines.Line2D object at 0x10263b890>]
>>> fig1.savefig('fig1.png')
>>> fig2.savefig('fig2.png')
...which produces these two plots into their own ".png" files:
To save them to the same file, use subplots:
>>> from matplotlib import pyplot as plt
>>> fig = plt.figure()
>>> axis1 = fig.add_subplot(211)
>>> axis1.plot(range(10))
>>> axis2 = fig.add_subplot(212)
>>> axis2.plot(range(10,20))
>>> fig.savefig('multipleplots.png')
The above script produces this single ".png" file:
I struggled with the same issue. I was trying to put 2,000 scatter plots into a single .pdf. I was able to start the procedure, but it aborted after a few hundred.
Even when I created six scatter charts into one .pdf, the .pdf file was enormous (like 7mb) for just six .jpg's that were 30kb each. When I opened the .pdf, it appeared that the .pdf was painting every point on the chart (each chart had thousands of points) instead of displaying an image. Some day, I will figure out the correct options, but here is a quick and dirty work-around. I printed the scatter plots to individual .jpg files in a local directory.

How can I automatically combine matplotlib graphs with Adobe Illustrator vector illustrations?

I'm currently writing a scientific paper and am generating most of the figures using matplotlib. I have a pipeline set up using a makefile that regenerates all of my plots whenever I update the data. My problem is that the figures are made up multiple panels, and some of those panels should contain vector illustrations which I've created using Adobe Illustrator. How can I automatically combine the graphs with the illustrations when I update my raw data? I could save the vector illustrations in a raster format and then display them using matplotlib's imshow function, but I want the output to be a vector to ensure the best possible print quality.
After some more extensive googling I found this old message on the matplotlib mailing list:
The thread suggests using the python library PyX, which works well for me.
I can save both the illustrator diagrams and the matplotlib plots as .eps files, and then combine them together like this:
import pyx
c = pyx.canvas.canvas()
c.insert(pyx.epsfile.epsfile(0, 0, "1.eps", align="tl"))
c.insert(pyx.epsfile.epsfile(0,0,"2.eps", align="tr"))
c.writeEPSfile("combined.eps")
I found this example in the svgutils documentation which outlines how to combine matplotlib-generated SVGs into a single plot.
Here's the example from that page:
import svgutils.transform as sg
import sys
#create new SVG figure
fig = sg.SVGFigure("16cm", "6.5cm")
# load matpotlib-generated figures
fig1 = sg.fromfile('sigmoid_fit.svg')
fig2 = sg.fromfile('anscombe.svg')
# get the plot objects
plot1 = fig1.getroot()
plot2 = fig2.getroot()
plot2.moveto(280, 0, scale=0.5)
# add text labels
txt1 = sg.TextElement(25,20, "A", size=12, weight="bold")
txt2 = sg.TextElement(305,20, "B", size=12, weight="bold")
# append plots and labels to figure
fig.append([plot1, plot2])
fig.append([txt1, txt2])
# save generated SVG files
fig.save("fig_final.svg")

Python saving multiple figures into one PDF file

In python (for one figure created in a GUI) I was able to save the figure under .jpg and also .pdf by either using:
plt.savefig(filename1 + '.pdf')
or
plt.savefig(filename1 + '.jpg')
Using one file I would like to save multiple figures in either .pdf or .jpg (just like its done in math lab). Can anybody please help with this?
Use PdfPages to solve your problem. Pass your figure object to the savefig method.
For example, if you have a whole pile of figure objects open and you want to save them into a multi-page PDF, you might do:
import matplotlib.backends.backend_pdf
pdf = matplotlib.backends.backend_pdf.PdfPages("output.pdf")
for fig in xrange(1, figure().number): ## will open an empty extra figure :(
pdf.savefig( fig )
pdf.close()
Do you mean save multiple figures into one file, or save multiple figures using one script?
Here's how you can save two different figures using one script.
>>> from matplotlib import pyplot as plt
>>> fig1 = plt.figure()
>>> plt.plot(range(10))
[<matplotlib.lines.Line2D object at 0x10261bd90>]
>>> fig2 = plt.figure()
>>> plt.plot(range(10,20))
[<matplotlib.lines.Line2D object at 0x10263b890>]
>>> fig1.savefig('fig1.png')
>>> fig2.savefig('fig2.png')
...which produces these two plots into their own ".png" files:
To save them to the same file, use subplots:
>>> from matplotlib import pyplot as plt
>>> fig = plt.figure()
>>> axis1 = fig.add_subplot(211)
>>> axis1.plot(range(10))
>>> axis2 = fig.add_subplot(212)
>>> axis2.plot(range(10,20))
>>> fig.savefig('multipleplots.png')
The above script produces this single ".png" file:
I struggled with the same issue. I was trying to put 2,000 scatter plots into a single .pdf. I was able to start the procedure, but it aborted after a few hundred.
Even when I created six scatter charts into one .pdf, the .pdf file was enormous (like 7mb) for just six .jpg's that were 30kb each. When I opened the .pdf, it appeared that the .pdf was painting every point on the chart (each chart had thousands of points) instead of displaying an image. Some day, I will figure out the correct options, but here is a quick and dirty work-around. I printed the scatter plots to individual .jpg files in a local directory.

Custom Artist In Matplotlib Legend

I have a program using PtQt that utilizes matplotlib to do some plot rendering. For saving images, I would like to make use of the legend to render a custom image (additionally the built-in draggable feature makes this very appealing). I'm reading up on the legend, but I can't seem to figure out how to make a legend that calls my own paintEvent() method for Qt in which I can render custom images.
In case this approach is terrible, here's my goal: I want to put a image (rendered inside the program by Qt) either inside the plot window or find a way to append this image on top of the exported figure.
Here's a screenshot of what the output looks like now:
I'd like to take the DAIP... sequence at the top and have that exported with the figure.
Hopefully someone has tackled a similar problem before.
I solved it by using the OffsetImage and AnnotationBBox features of matplotlib after saving the image to a temporary png file. For some reason keeping it as a temporary file didn't work well.
Briefly:
#draw stuff onto QPixmap named pix
byteArray = QByteArray()
buffer = QBuffer(byteArray)
buffer.open(QIODevice.WriteOnly)
pix.save(buffer, 'PNG')
stringIO = StringIO(byteArray)
stringIO.seek(0)
tfile = tempfile.NamedTemporaryFile(suffix=".png", mode="wb", delete=False)
tfile.write(stringIO.buf)
tfile.close()
imagebox = mpl.offsetbox.OffsetImage(mpl._png.read_png(tfile.name),zoom=zlvl)
ab = mpl.offsetbox.AnnotationBbox(imagebox, [w/2,0],frameon=False)
ab.set_figure(self.canvas.figure)
ab.draggable()
self.subplot.axes.add_artist(ab)
os.remove(tfile.name)

Categories

Resources