Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically cropping an image with python/PIL

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?

like image 627
dimka Avatar asked Jan 08 '13 08:01

dimka


People also ask

How do I automatically crop photos?

Go to File > Choose Automate > Crop and Straighten Photos. Photoshop handles this as a batch process. You don't have to select anything manually. It recognizes the scanned image and automatically crops, straightens, and separates each photo into its individual image.

How do I crop part of an image in Python?

The crop() function of the image class in Pillow requires the portion to be cropped as rectangle. The rectangle portion to be cropped from an image is specified as a four-element tuple and returns the rectangle portion of the image that has been cropped as an image Object.

Can we crop image in Python?

In Python, you crop the image using the same method as NumPy array slicing. To slice an array, you need to specify the start and end index of the first as well as the second dimension. The first dimension is always the number of rows or the height of the image.


1 Answers

Install Pillow

pip install Pillow 

and use as

from PIL 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.

like image 79
sneawo Avatar answered Oct 11 '22 05:10

sneawo