简体   繁体   English

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

[英]How do I crop multiple images using PIL?

I've just started using PIL with python and I need help with detecting the photos and cropping out multiple images on a single white background with different sizes. 我刚刚开始将PIL与python结合使用,并且需要帮助您检测照片并在不同大小的单个白色背景上裁剪出多个图像。 I've used Image.crop and ImageChop.difference , but that only crops out one image. 我使用过Image.cropImageChop.difference ,但是只能ImageChop.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()

I think something like the following is what you are looking for: 我认为您正在寻找以下内容:

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)


The program works by taking an input image ( download.jpg in this case), looping through a list of (x1, y1, x2, y2) coordinates which represent areas of the images to be cropped, and then passes each image to the crop_image() function which takes in the image to be cropped, the coordinates and the new filename for the image to be saved as. 该程序通过获取输入图像(在这种情况下为download.jpg ),循环显示代表要裁剪的图像区域的(x1, y1, x2, y2)坐标列表,然后将每个图像传递给crop_image()函数,用于获取要裁剪的图像,坐标以及要另存为该图像的新文件名。


The resulting files are saved as download_cropped0.jpg and download_cropped1.jpg (in this example). 生成的文件另存为download_cropped0.jpgdownload_cropped1.jpg (在此示例中)。 If you want to crop more areas in the image, you'll need to add more tuples in the form of (x1, y1, x2, y2) to the crop_areas list. 如果要在图像中裁剪更多区域,则需要以(x1, y1, x2, y2)的形式添加更多元组到crop_areas列表中。 You can use a program like paint or photshop to get the coordinates of the image you want to crop from and to. 您可以使用诸如paint或photshop之类的程序来获取要裁剪的图像的坐标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM