Is there a simple solution to trim whitespace on the image in PIL?
ImageMagick has easy support for it in the following way:
convert test.jpeg -fuzz 7% -trim test_trimmed.jpeg I found a solution for PIL:
from PIL import Image, ImageChops def trim(im, border): bg = Image.new(im.mode, im.size, border) diff = ImageChops.difference(im, bg) bbox = diff.getbbox() if bbox: return im.crop(bbox) But this solution has disadvantages:
border color, it is not a big deal for me, my images has a white background-fuzz key. To add some fuzzy cropping. as I can have some jpeg compression artifacts and unneeded huge shadows.Maybe PIL has some built-in functions for it? Or there is some fast solution?
The strip() method is the most commonly accepted method to remove whitespaces in Python. It is a Python built-in function that trims a string by removing all leading and trailing whitespaces.
I don't think there is anything built in to PIL that can do this. But I've modified your code so it will do it.
getpixel, so you don't need to pass the colour.100, 100, 100 (in my example) to zero. So is a neat way to remove any 'wobble' resulting from compression.Code:
from PIL import Image, ImageChops def trim(im): bg = Image.new(im.mode, im.size, im.getpixel((0,0))) diff = ImageChops.difference(im, bg) diff = ImageChops.add(diff, diff, 2.0, -100) bbox = diff.getbbox() if bbox: return im.crop(bbox) im = Image.open("bord3.jpg") im = trim(im) im.show() Heavily compressed jpeg:
Cropped: 
Noisy jpeg:
Cropped: 
Use wand http://docs.wand-py.org/en/0.3-maintenance/wand/image.html
trim(color=None, fuzz=0) Remove solid border from image. Uses top left pixel as a guide by default, or you can also specify the color to remove.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With