2

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

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 2
    It totally depends on what graphics / imaging module you are using (but you have not specified in your question or its tags). – martineau Jul 07 '22 at 16:26
  • I have edit with the code I use to display and save the image, does that help ? I'm willing to change how I do it of course if anyone have a solution using something else ^^ – chang thenoob Jul 08 '22 at 08:23
  • 1
    You could create the image a little larger than you need (so you have sufficient quality) then resize it using PIL/Pillow or OpenCV in Python, or just with **ImageMagick** in the Terminal `magick INPUT.PNG -resize '11230x11229!' RESULT.PNG` – Mark Setchell Jul 08 '22 at 08:35
  • Thanks for your suggestion, I will try some resizing with pil/pillow or opencv. Just a question, I saw number of times suggestion about commands in the "terminal" like that. What is the "terminal" and how can I access it please ? Sorry I'm beginner – chang thenoob Jul 08 '22 at 08:52
  • It's called **Command Prompt** if you are on Windows and in that case the command is `magick INPUT.PNG -resize 11230x11229! RESULT.PNG` – Mark Setchell Jul 08 '22 at 09:00
  • I'm not familiar with this, so far I only managed to have an error saying the name "magick" is unknown, not sure if I'm using it right – chang thenoob Jul 08 '22 at 11:52
  • If you have an older version 6 ImageMagick, you'd need `convert INPUT....` rather than `magick INPUT ...`. – Mark Setchell Jul 08 '22 at 12:01
  • Or you may not have set your PATH correctly to include the directory where ImageMagick is installed. – Mark Setchell Jul 08 '22 at 12:02
  • Or more obviously, you haven't installed ImageMagick at all. – nigh_anxiety Jul 08 '22 at 13:35
  • 1
    You can do it with the Pillow fork of the `PIL` (Python Graphics Library) which you can get via [pypi](https://pypi.org/project/Pillow/). Note you can download & install it via `pip` (see [installation instructions](https://pillow.readthedocs.io/en/latest/installation.html)). Note that using it does not involve the terminal. – martineau Jul 08 '22 at 13:56

2 Answers2

1

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

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()
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70