Reputation: 53
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.
I've used Image.crop
and ImageChop.difference
, but that only crops out one image.
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()
Upvotes: 1
Views: 7836
Reputation:
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.
The resulting files are saved as download_cropped0.jpg
and download_cropped1.jpg
(in this example). 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. You can use a program like paint or photshop to get the coordinates of the image you want to crop from and to.
Upvotes: 3