Specifying and Saving a Figure with Exact Size in Pixels

Specifying and saving a figure with exact size in pixels

Matplotlib doesn't work with pixels directly, but rather physical sizes and DPI. If you want to display a figure with a certain pixel size, you need to know the DPI of your monitor. For example this link will detect that for you.

If you have an image of 3841x7195 pixels it is unlikely that you monitor will be that large, so you won't be able to show a figure of that size (matplotlib requires the figure to fit in the screen, if you ask for a size too large it will shrink to the screen size). Let's imagine you want an 800x800 pixel image just for an example. Here's how to show an 800x800 pixel image in my monitor (my_dpi=96):

plt.figure(figsize=(800/my_dpi, 800/my_dpi), dpi=my_dpi)

So you basically just divide the dimensions in inches by your DPI.

If you want to save a figure of a specific size, then it is a different matter. Screen DPIs are not so important anymore (unless you ask for a figure that won't fit in the screen). Using the same example of the 800x800 pixel figure, we can save it in different resolutions using the dpi keyword of savefig. To save it in the same resolution as the screen just use the same dpi:

plt.savefig('my_fig.png', dpi=my_dpi)

To to save it as an 8000x8000 pixel image, use a dpi 10 times larger:

plt.savefig('my_fig.png', dpi=my_dpi * 10)

Note that the setting of the DPI is not supported by all backends. Here, the PNG backend is used, but the pdf and ps backends will implement the size differently. Also, changing the DPI and sizes will also affect things like fontsize. A larger DPI will keep the same relative sizes of fonts and elements, but if you want smaller fonts for a larger figure you need to increase the physical size instead of the DPI.

Getting back to your example, if you want to save a image with 3841 x 7195 pixels, you could do the following:

plt.figure(figsize=(3.841, 7.195), dpi=100)
( your code ...)
plt.savefig('myfig.png', dpi=1000)

Note that I used the figure dpi of 100 to fit in most screens, but saved with dpi=1000 to achieve the required resolution. In my system this produces a png with 3840x7190 pixels -- it seems that the DPI saved is always 0.02 pixels/inch smaller than the selected value, which will have a (small) effect on large image sizes. Some more discussion of this here.

Saving figure with exact pixel size

I don't know how to "accept as answer" the comments under my posts? So I just write the answer here. It's by using the PIL package that @martineau and @Mark Setchell suggested that it worked like a charm:

from PIL import Image
img = Image.open('myImage.png')
newsize = (11230, 11229)
img = img.resize(newsize)
img.save('myResizedImage.png')

Python save matplotlib figure with exact pixel size

You can use subplots_adjust to set the padding around your plot.

myFig.subplots_adjust(bottom=0.,left=0.,right=1.,top=1.)

Sample Image

Saving a figure vis matplotlib by adapting inches to pixels

Your DPI is directly related to figsize (which is defined in inches). DPI (dots per inch) multiplied by your width/height from figsize will let you calculate the size in terms of pixels. The snipper below would generate a figure with your required dimensions. Please note, the aspect ratio is NOT the same between what you had in your figsize and label.

label = np.zeros((230,256))

my_dpi = 96

w = 230./my_dpi
h = 256./my_dpi

# Create a figure. Equal aspect so circles look circular
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_aspect('equal')
ax.set_axis_off()
# Show the image
ax.imshow(label)

circ1 = Circle((28,64),10, color='white')
circ1 = Circle((26,65),13, color='white')
circ2 = Circle((100,65),13, color='white')
circ3 = Circle((172,65),11, color='white')
circ4 = Circle((247,65),11, color='white')
circ5 = Circle((315,65),10, color='white')
ax.add_patch(circ1)
ax.add_patch(circ2)
ax.add_patch(circ3)
ax.add_patch(circ4)
ax.add_patch(circ5)
# Show the image
plt.show()

fig.set_size_inches(w, h, forward=True)
fig.tight_layout()
fig.savefig(nimage[23].split('.')[0]+'_gt.jpg', dpi=my_dpi)

How to save a matplotlib.pypot figure as an image with required pixel size?

Try adjusting the dpi argument in savefig. From the docs:
"dpi : the resolution in dots per inch".
https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.savefig.html

The actual number of pixels may vary depending on your screen resolution.

For a more detailed explanation, see this answer:
Specifying and saving a figure with exact size in pixels

How to change the size of image created by savefig (seaborn heatmap ) to 1000*1000 px?

plt.subplots_adjust(left=0, bottom=0, right=1, top=1) would reduce the whitespace. plt.axis('off') turns off the axes.

Also note that figsize=(1,1) might give strange results when working with text. figsize=(10,10) and plt.savefig(..., dpi=100) could work better.

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from scipy.ndimage import gaussian_filter

w = 1000
h = 1000
plt.figure(figsize=(w / 100, h / 100))
ax = sns.heatmap(gaussian_filter(np.random.rand(50, 50), 5), xticklabels=False, yticklabels=False, cbar=False)
plt.subplots_adjust(left=0, bottom=0, right=1, top=1)
plt.axis('off')
plt.savefig('tempFile.png', dpi=100, pad_inches=0)

1000x1000 bitmap



Related Topics



Leave a reply



Submit