I have to edit few image files using python. I have to open each image file, add few points at particular location & save the new edited image file(For fd my post-processing work).
Problem I am facing is:
1) I could not resize my plot axis. My plot axis should be 0-1 on both x &y with out any loss in image quality.
2) I could not save the edited image file, only the original file is getting saved.
This is what I tried:
im = Image.open('vortex.png')
implot = plt.plot(im)
fig, ax= plt.subplots()
myaximage = ax.imshow(im, aspect='auto', extent=(0,1,0,1),
alpha=0.5, origin='upper',
zorder=-2)
plt.implot([0.5], [0.5])
plt.show()
im.save("new","png")
Besides some small problems with your code, it seems you're basing your work on a wrong assumption: that you can turn a image into a matplotlib plot.
An image is simply a collection of pixels. While your brain interprets it as a plot, with a axis, and maybe a grid, you can't expect the computer to do so. You can't manipulate a collection of pixels as if it were a plot - it isn't.
You need to forget about matplotlib and use the image editing resourses of PIL.
Not sure about the axis change, but the saving of the file, see this post:
Python Imaging Library save function syntax
From the PIL Handbook:
im.save(outfile, options...)
im.save(outfile, format, options...)
Simplest case:
im.save('my_image.png')
Related
In matplotlib, I am using LineCollection to draw and color the countries, where the boundaries of the counties are given. When I am saving the figure as a pdf file:
fig.savefig('filename.pdf',dpi=300)
the figure size are quite big. However, on saving them as png file:
fig.savefig('filename.png',dpi=300)
and then converting them to pdf using linux convert command the files are small. I tried reducing the dpi, however that do not change the pdf file size. Is there a way the figures can be saved directly as smaller-pdf files from matplotlib?
The PDF is larger, since it contains all the vector information. By saving a PNG, you produce a rasterized image. It seems that in your case, you can produce a smaller PDF by rasterizing the plot directly:
plt.plot(x, y, 'r-', rasterized=True)
Here, x, y are some plot coordinates. You basically have to use the additionally keyword argument raterized to achieve the effect.
I think using "rasterized = True" effectively saves the image similarly to png format. When you zoom in, you will see blurring pixels.
If you want the figures to be high quality, my suggestion is to sample from the data and make a plot. The pdf file size is roughly the amount of data points it need to remember.
I want to save an image plotted with matplotlib. For that, I use the function savefig which has different parameters.
The problem is that when I saved the image, this function add additional white pixel.
In short, I would like to save the image I draw with the original size. In other words, if the data I draw has a dimension of 1000x560, I save the image with those dimensions without additional white parts.
Thus in this way a pixel of the saved image coincides with the pixel that the figure of matplotlib can see.
I'm using python 2.7
Can anyone help please?
Thanks
from matplotlib import pyplot as plt
plt.savefig('foo.png', bbox_inches='tight')
I have a problem with Matplotlib. I usually make big plots with many data points and then, after zooming or setting limits, I save in pdf only a specific subset of the original plot. The problem comes when I open this file: matplotlib saves all the data into the pdf making not visible the one outside of the range. This makes almost impossible to open afterwards those plots or to import them into latex.
Any idea of how I could solve this problem is really welcome.
Thanks a lot
If you don't have a requirement to use PDF figures, you can save the matplotlib figures as .png; this format just contains the data on the screen, e.g. I tried saving a large scatter plot as PDF, its size was 198M; as png it came out as 270K; plus I've never had any problems using png inside latex.
I have not tested that this will work, but it might be worth rasterizing some of the artists:
fig, ax = plt.subplots()
ax.imshow(..., rasterized=True)
fig.savefig('test.png', dpi=600)
which will rasterize the artist when saving to vector formats. If you use a high enough dpi this should give you reasonable quality.
My usual workflow is to generate a plot using matplotlib, save the plot as a pdf using savefig(), and then open the plot in Adobe Illustrator to do final tweaking. Every pdf created by matplotlib has a clipping mask around the border of the content. I find it quite annoying to always release the clipping mask and then delete the clipping bounding box before I begin adjusting my pdf. Is there some way to eliminate this clipping behavior?
To make this more concrete, here is an example,
import matplotlib.pylab as plt
fig = plt.figure(figsize = (5,5))
ax = plt.subplot(111)
ax.plot([0,1], [0,1])
plt.savefig('Test.pdf')
which creates a pdf with a clipping mask around the outside edges, even though there is nothing to clip.
I noticed that I can set fig.set_clip_on=False, but it does not do anything. In fact, if I set fig.set_clip_on=False and directly afterwards query fig.get_clip_on, it returns True.
Any suggestions to get rid of the clipping bbox?
How can I save Python plots at very high quality?
That is, when I keep zooming in on the object saved in a PDF file, why isn't there any blurring?
Also, what would be the best mode to save it in?
png, eps? Or some other? I can't do pdf, because there is a hidden number that happens that mess with Latexmk compilation.
If you are using Matplotlib and are trying to get good figures in a LaTeX document, save as an EPS. Specifically, try something like this after running the commands to plot the image:
plt.savefig('destination_path.eps', format='eps')
I have found that EPS files work best and the dpi parameter is what really makes them look good in a document.
To specify the orientation of the figure before saving, simply call the following before the plt.savefig call, but after creating the plot (assuming you have plotted using an axes with the name ax):
ax.view_init(elev=elevation_angle, azim=azimuthal_angle)
Where elevation_angle is a number (in degrees) specifying the polar angle (down from vertical z axis) and the azimuthal_angle specifies the azimuthal angle (around the z axis).
I find that it is easiest to determine these values by first plotting the image and then rotating it and watching the current values of the angles appear towards the bottom of the window just below the actual plot. Keep in mind that the x, y, z, positions appear by default, but they are replaced with the two angles when you start to click+drag+rotate the image.
Just to add my results, also using Matplotlib.
.eps made all my text bold and removed transparency. .svg gave me high-resolution pictures that actually looked like my graph.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# Do the plot code
fig.savefig('myimage.svg', format='svg', dpi=1200)
I used 1200 dpi because a lot of scientific journals require images in 1200 / 600 / 300 dpi, depending on what the image is of. Convert to desired dpi and format in GIMP or Inkscape.
Obviously the dpi doesn't matter since .svg are vector graphics and have "infinite resolution".
You can save to a figure that is 1920x1080 (or 1080p) using:
fig = plt.figure(figsize=(19.20,10.80))
You can also go much higher or lower. The above solutions work well for printing, but these days you want the created image to go into a PNG/JPG or appear in a wide screen format.
Okay, I found spencerlyon2's answer working. However, in case anybody would find himself/herself not knowing what to do with that one line, I had to do it this way:
beingsaved = plt.figure()
# Some scatter plots
plt.scatter(X_1_x, X_1_y)
plt.scatter(X_2_x, X_2_y)
beingsaved.savefig('destination_path.eps', format='eps', dpi=1000)
In case you are working with seaborn plots, instead of Matplotlib, you can save a .png image like this:
Let's suppose you have a matrix object (either Pandas or NumPy), and you want to take a heatmap:
import seaborn as sb
image = sb.heatmap(matrix) # This gets you the heatmap
image.figure.savefig("C:/Your/Path/ ... /your_image.png") # This saves it
This code is compatible with the latest version of Seaborn. Other code around Stack Overflow worked only for previous versions.
Another way I like is this. I set the size of the next image as follows:
plt.subplots(figsize=(15,15))
And then later I plot the output in the console, from which I can copy-paste it where I want. (Since Seaborn is built on top of Matplotlib, there will not be any problem.)