【问题标题】:How do I crop multiple images using PIL?如何使用 PIL 裁剪多张图像?
【发布时间】:2018-12-11 23:25:48
【问题描述】:

我刚刚开始在 python 中使用 PIL,我需要帮助来检测照片并在单个白色背景上裁剪出不同大小的多个图像。 我用过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()

【问题讨论】:

  • 可能会循环你正在做的事情并传递不同的图像?
  • 最好分享你的代码,见How do I ask a good question?
  • 您要从白色背景裁剪的图像是否都相同大小?如果是这样,您可以将图像分成相等的大小,然后循环遍历图像并裁剪它。否则,您可以添加像素偏移以在列表中进行裁剪。例如,如果您的图像为 900 像素,并且您希望每 300 像素裁剪一次图像,您可以在 0-299 像素、300-599 像素和 600-899 像素处裁剪图像
  • 请澄清您所说的“在白色背景上裁剪出多个图像”是什么意思。另外,这与将它们作为不同文件打开有什么关系?
  • 您的意思是您只有一个文件,就像扫描仪的平台上排列的 6 张图像一样?如何向我们展示输入和预期输出?

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


【解决方案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)坐标列表,然后将每个图像传递给crop_image()函数,该函数接收要裁剪的图像、要保存的图像的坐标和新文件名。


结果文件保存为download_cropped0.jpgdownload_cropped1.jpg(在本例中)。如果要裁剪图像中的更多区域,则需要以(x1, y1, x2, y2) 的形式将更多元组添加到crop_areas 列表中。您可以使用paint或photoshop之类的程序来获取您想要裁剪的图像的坐标。

【讨论】:

    猜你喜欢
    • 2012-04-16
    • 2019-03-26
    • 2011-08-09
    • 2012-10-01
    • 1970-01-01
    • 2013-03-06
    • 2012-12-22
    • 2017-01-18
    • 2011-09-21
    相关资源
    最近更新 更多