使用 python/PIL 自动裁剪图像 [英] Automatically cropping an image with python/PIL
问题描述
谁能帮我弄清楚我的图像自动裁剪脚本中发生了什么?我有一个带有大透明区域/空间的 png 图像.我希望能够自动裁剪该空间并留下必需品.原始图像有一个正方形的画布,最好是矩形的,只包含分子.
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.
这是原图:
通过谷歌搜索,我发现 PIL/python 代码被报告可以工作,但在我手中,运行下面的代码过度裁剪图像.
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')
输出是这样的:
任何更熟悉图像处理/PLI 的人能帮我找出问题吗?
Can anyone more familiar with image-processing/PLI can help me figure out the issue?
推荐答案
您可以使用 numpy,将图像转换为数组,找到所有非空的列和行,然后从这些列和行创建图像:
You can use numpy, convert the image to array, find all non-empty columns and rows and then create an image from these:
import Image
import numpy as np
image=Image.open('L_2d.png')
image.load()
image_data = np.asarray(image)
image_data_bw = image_data.max(axis=2)
non_empty_columns = np.where(image_data_bw.max(axis=0)>0)[0]
non_empty_rows = np.where(image_data_bw.max(axis=1)>0)[0]
cropBox = (min(non_empty_rows), max(non_empty_rows), min(non_empty_columns), max(non_empty_columns))
image_data_new = image_data[cropBox[0]:cropBox[1]+1, cropBox[2]:cropBox[3]+1 , :]
new_image = Image.fromarray(image_data_new)
new_image.save('L_2d_cropped.png')
结果看起来像
如果有什么不清楚的,尽管问.
If anything is unclear, just ask.
这篇关于使用 python/PIL 自动裁剪图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!