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:
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:
Can anyone more familiar with image-processing/PLI can help me figure out the issue?
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.
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.
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.
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.
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