[英]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.