使用python/PIL自动裁剪图像

2024-09-28 21:26:34 发布

您现在位置:Python中文网/ 问答频道 /正文

有谁能帮我弄清楚我的图像自动裁剪脚本中发生了什么?我有一个png图像,有一个很大的透明区域/空间。我想能够自动裁剪出空间,留下必需品。原始图像有一个正方形的画布,最理想的情况是它是矩形的,只封装了分子。

原图如下: Original Image

在google上搜索时,我发现了PIL/python代码,据报道这些代码在我的手中可以工作,但是在裁剪图像的时候运行下面的代码。

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')

结果是:script's output

熟悉图像处理/PLI的人能帮我解决这个问题吗?


Tags: 代码图像imageimportpng空间printcropped
3条回答

我测试了这篇文章中的大部分答案,但是,我最终得到了自己的答案。我用的是PythonPython。

from PIL import Image, ImageChops

def trim(im):
    bg = Image.new(im.mode, im.size, im.getpixel((0,0)))
    diff = ImageChops.difference(im, bg)
    diff = ImageChops.add(diff, diff, 2.0, -100)
    #Bounding box given as a 4-tuple defining the left, upper, right, and lower pixel coordinates.
    #If the image is completely empty, this method returns None.
    bbox = diff.getbbox()
    if bbox:
        return im.crop(bbox)

if __name__ == "__main__":
    bg = Image.open("test.jpg") # The image to be cropped
    new_im = trim(bg)
    new_im.show()

对我来说,它的作用是:

import Image

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

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

当您通过mask=imageComponents[3]搜索边界时,只能通过蓝色通道搜索。

可以使用numpy,将图像转换为数组,查找所有非空的列和行,然后从中创建图像:

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')

结果看起来像 cropped image

如果有什么不清楚的,尽管问。

相关问题 更多 >