[英]How do you detect and crop multiple images on a single white background using PIL?
[英]How do I crop multiple images using PIL?
我刚刚开始将PIL与python结合使用,并且需要帮助您检测照片并在不同大小的单个白色背景上裁剪出多个图像。 我使用过Image.crop
和ImageChop.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()
我认为您正在寻找以下内容:
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)
坐标列表,然后将每个图像传递给crop_image()
函数,用于获取要裁剪的图像,坐标以及要另存为该图像的新文件名。
生成的文件另存为download_cropped0.jpg
和download_cropped1.jpg
(在此示例中)。 如果要在图像中裁剪更多区域,则需要以(x1, y1, x2, y2)
的形式添加更多元组到crop_areas
列表中。 您可以使用诸如paint或photshop之类的程序来获取要裁剪的图像的坐标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.