How To Remove Whitespace From An Image In Python?
I have a set of images that are output from a code, and I want to be able to remove all of the excess whitespace within the image so that it reduces the image to only the text with
Solution 1:
I think this is what you want - a kind of double-matted surround:
#!/usr/bin/env python3
from PIL import Image, ImageDraw, ImageOps
# Open input image
im = Image.open('zHZB9.png')
# Get rid of existing black border by flood-filling with white from top-left corner
ImageDraw.floodfill(im,xy=(0,0),value=(255,255,255),thresh=10)
# Get bounding box of text and trim to it
bbox = ImageOps.invert(im).getbbox()
trimmed = im.crop(bbox)
# Add new white border, then new black, then new white border
res = ImageOps.expand(trimmed, border=10, fill=(255,255,255))
res = ImageOps.expand(res, border=5, fill=(0,0,0))
res = ImageOps.expand(res, border=5, fill=(255,255,255))
res.save('result.png')
Post a Comment for "How To Remove Whitespace From An Image In Python?"