Automatically cropping an image with python/PIL

dimka picture dimka · Jan 8, 2013 · Viewed 39.4k times · Source

Can anyone help me figure out what's happening in my image auto-cropping script? I have a png image with a large transparent area/space. I would like to be able to automatically crop that space out and leave the essentials. Original image has a squared canvas, optimally it would be rectangular, encapsulating just the molecule.

here's the original image: Original Image

Doing some googling i came across PIL/python code that was reported to work, however in my hands, running the code below over-crops the image.

import Image
import sys

image=Image.open('L_2d.png')
image.load()

imageSize = image.size
imageBox = image.getbbox()

imageComponents = image.split()

rgbImage = Image.new("RGB", imageSize, (0,0,0))
rgbImage.paste(image, mask=imageComponents[3])
croppedBox = rgbImage.getbbox()
print imageBox
print croppedBox
if imageBox != croppedBox:
    cropped=image.crop(croppedBox)
    print 'L_2d.png:', "Size:", imageSize, "New Size:",croppedBox
    cropped.save('L_2d_cropped.png')

the output is this:script's output

Can anyone more familiar with image-processing/PLI can help me figure out the issue?

Answer

sneawo picture sneawo · Jan 8, 2013

For me it works as:

import Image

image=Image.open('L_2d.png')

imageBox = image.getbbox()
cropped=image.crop(imageBox)
cropped.save('L_2d_cropped.png')

When you search for boundaries by mask=imageComponents[3], you search only by blue channel.