Removing white space around a saved image
Delete that pesky whitespace in an image using Pillow's getbbox()
function for automatic trim. getbbox()
computes the bounding box of the non-empty spots and crop()
function trims away what doesn't belong. Here's the crux:
Invoke trim_whitespace()
with your image file path to get a whitespace-free image.
Trimming alternates and optimizations
Sometimes, the image might be a matplotlib plot. Worry not! There's a treasure trove of options to bid farewell to the unwanted white border, without even touching an image editor.
Tightening the image in matplotlib
To make your image fit snug, like skinny jeans, use bbox_inches='tight'
and pad_inches=0
in plt.savefig()
. An example, tailored for you:
Exile padding and axis
If axis extras are taking up space, send them to oblivion with plt.gca().set_axis_off()
. Set the matplotlib plot margins to zero using plt.margins(0,0)
:
plt.subplots_adjust()
lets you say no to subplot parameters causing unwanted space:
Sweet transparency: invisible backgrounds
White backgrounds can be misleading. But no more! Use transparent=True
for that seamless integration wherever this image goes:
All in one function: plot and trim
Combine both, matplotlib and Pillow, to create an all-in-one function for plot and trim:
Why settle for one? Do both generations of trim.
Beyond static images: the method to the madness
It's not always about static images. The plot thickens as we venture into the realms of web and GUIs.
Web rendering perils
On the web, CSS can reintroduce whitespace. Fight this by setting the style
attribute in your image tag:
Look ma, no extra space!
Gui framework nuances
Working with GUI frameworks? Ensure you're using compatible classes. Like PhotoImage
for Tkinter. And watch out for excessive margins handed by the GUI elements:
Slim fit images, for the win.
Potential pitfalls: edge cases
There might be cases, like shadows or anti-aliasing, where whitespace clings on like a stubborn sticker. What do we do? We adapt:
- Adjustment in Pillow trim: Use
ImageOps.expand
beforegetbbox()
to handle anti-aliasing. - Threshold finetuning in matplotlib: Get granular with the
extent
parameter or custom clipping paths. - Testing: Iteratively test through visual inspection or image comparison tests.
Was this article helpful?