Saving Image with Exact Pixel Size Using Matplotlib
In need of saving a figure with a precise pixel size, we delve into the world of Matplotlib. This library operates with physical sizes and DPI, but with a keen understanding of your monitor's DPI, you can seamlessly display images of specific pixel dimensions.
Understanding Matplotlib's Dimensions
Matplotlib necessitates figure sizes to be defined in inches, accompanied by DPI. To display a figure with a specific pixel size, you'll require your monitor's DPI. For instance, an 800x800 pixel image can be shown using:
plt.figure(figsize=(800/my_dpi, 800/my_dpi), dpi=my_dpi)
where my_dpi represents your monitor's DPI.
Saving in a Specified Resolution
Saving a figure with a particular size is a distinct operation. Screen DPIs are less significant here, and the dpi keyword in savefig allows us to control the resolution of the saved image.
To save an 800x800 pixel figure in the same resolution as your screen, use:
plt.savefig('my_fig.png', dpi=my_dpi)
For an 8000x8000 pixel image, increase the DPI:
plt.savefig('my_fig.png', dpi=my_dpi * 10)
Exemplifying the Solution
In your case, to save an image with 3841 x 7195 pixels, follow these steps:
plt.figure(figsize=(3.841, 7.195), dpi=100)
# Your code for the image
plt.savefig('myfig.png', dpi=1000)
Here, the figure DPI is set to 100 for screen compatibility, but the saved image's DPI is elevated to 1000 to achieve the desired resolution. Note that the DPI used for saving may slightly deviate from the requested value, as explained by previous discussions.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3