本文介绍了使用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.

这里是原始图像:

here's the original image:

做了一些谷歌搜索我遇到了报告工作的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')

结果看起来像

The result looks like

如果有任何不清楚的地方,请询问。

If anything is unclear, just ask.

这篇关于使用python / PIL自动裁剪图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 04:27
查看更多