如何使用PIL裁剪多个图像?

时间:2018-07-03 15:21:20

标签: python image python-imaging-library crop removing-whitespace

我刚刚开始将PIL与python结合使用,并且需要帮助您检测照片并在单个白色背景上裁剪出具有不同大小的多个图像。 我使用过Image.cropImageChop.difference,但是只能裁剪出一张图像。

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)
bbox = diff.getbbox()
if bbox:
    return im.crop(bbox)
else:
    print("No image detected")


image1 = Image.open('multiple.jpg')
image2 = trim(image1)
image2.show()

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找如下内容:

import os

from PIL import Image

# Crops the image and saves it as "new_filename"
def crop_image(img, crop_area, new_filename):
    cropped_image = img.crop(crop_area)
    cropped_image.save(new_filename)

# The x, y coordinates of the areas to be cropped. (x1, y1, x2, y2)
crop_areas = [(180, 242, 330, 566), (340, 150, 900, 570)]

image_name = 'download.jpg'
img = Image.open(image_name)

# Loops through the "crop_areas" list and crops the image based on the coordinates in the list
for i, crop_area in enumerate(crop_areas):
    filename = os.path.splitext(image_name)[0]
    ext = os.path.splitext(image_name)[1]
    new_filename = filename + '_cropped' + str(i) + ext

    crop_image(img, crop_area, new_filename)


该程序通过获取输入图像(在这种情况下为download.jpg),循环显示代表要裁剪的图像区域的(x1, y1, x2, y2)坐标列表然后将每个图像传递到{{1 }}函数,用于获取要裁剪的图像,坐标和要另存为图像的新文件名。


结果文件另存为crop_image()download_cropped0.jpg(在此示例中)。如果要在图像中裁剪更多区域,则需要以download_cropped1.jpg的形式向(x1, y1, x2, y2)列表中添加更多元组。您可以使用Paint或Photshop之类的程序来获取要裁剪的图像的坐标。