Home > Article > Backend Development > How to Remove White Space Around Saved Images in Matplotlib?
When saving images after processing, it's common to encounter white space padding around the image. This can be frustrating, especially if youต้องการ a clean, cropped image.
For the snippet you provided:
<code class="python">fig = plt.figure(1) img = mpimg.imread("image.jpg") plt.imshow(img) ax = fig.add_subplot(1, 1, 1) extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) plt.savefig('1.png', bbox_inches=extent)</code>
Using tight= to savefig() does not solve the white space issue. Instead, try setting bbox_inches as a string:
<code class="python">plt.savefig("test.png", bbox_inches='tight')</code>
This should remove the white space padding, giving you a clean, cropped image.
Additionally, when using NetworkX to draw graphs on the figure, you may encounter white space around the saved image. To prevent this, ensure that bbox_inches="tight" is set in savefig().
The above is the detailed content of How to Remove White Space Around Saved Images in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!