Home > Net >  Saving figure with exact pixel size
Saving figure with exact pixel size

Time:07-09

How can I declare in python the pixel size (height and width) in which I want to save a figure (not just dpi, the exact number of pixels)? I've seen a lot of similar questions, but quite old and none of them seems to work (example1 example2).

I would also like to know if by doing so it's possible to change the aspect ratio of an image? I have a 11227x11229 pixels image, I would like to open it in python and save it as a 11230x11229, but so far can't achieve it.

Right now this is how I save my image, but I have to play with the "dpi" setting to approach the desired resolution. It's tedious, I can't always have the exact resolution and I can't change the aspect ratio like intended:

fig, ax = plt.subplots()
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
plt.axis('off')
plt.imshow(superpositionFINAL)
plt.savefig('myImage.png',  bbox_inches='tight', pad_inches = 0, dpi=2807.8)
plt.show()

Thanks

CodePudding user response:

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')

CodePudding user response:

You can do some math to figure out the DPI you need for a given figure size. Suppose your figure is 6.4in x 4.8in, and you want an image that is 640px x 480px, you know your DPI needs to be 100:

def export_fig(fig, filename, width, **kwrgs):
    figsize = fig.get_size_inches()
    dpi = width / figsize[0]
    fig.savefig(filename, dpi=dpi, **kwargs)

I provided a **kwargs in this function that just passes any keyword arguments to fig.savefig().

To use this function:

import numpy as np
from matplotlib import pyplot as plt

x = np.linspace(0, 2 * np.pi, 500)
y = np.sin(x)

fig = plt.figure(figsize=(6.4, 4.8))
plt.plot(x, y)

export_fig(fig, "./export.png", 640)

which gives you this image, with the correct dimensions:

enter image description here

enter image description here

If you find that your images have the wrong aspect ratio, you simply need to correct the figure size before exporting it as an image.

def resize_width_to_aspect_ratio(fig, desired_aspect_ratio):
    old_width, height = fig.get_size_inches()
    new_width = desired_aspect_ratio * current_size[1]
    fig.set_size_inches((new_width, height))

Since your desired aspect ratio is 11230:11229, you'd use this function like so:

fig, ax = plt.subplots()
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
plt.axis('off')
resize_width_to_aspect_ratio(fig, 11230/11229)
plt.imshow(superpositionFINAL)
export_fig(fig, "myImage.png", 11230, bbox_inches='tight', pad_inches=0)
plt.show()
  • Related