Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crop an image in the centre using PIL

How can I crop an image in the center? Because I know that the box is a 4-tuple defining the left, upper, right, and lower pixel coordinate but I don't know how to get these coordinates so it crops in the center.

like image 220
user2401069 Avatar asked May 20 '13 09:05

user2401069


People also ask

How do I crop a picture using PIL?

crop() method is used to crop a rectangular portion of any image. Parameters: box – a 4-tuple defining the left, upper, right, and lower pixel coordinate. Return type: Image (Returns a rectangular region as (left, upper, right, lower)-tuple).

How do you cut part of an image in Python?

The image processing library Pillow (PIL) of Python provides Image. crop() for cutting out a partial area of an image.


1 Answers

Assuming you know the size you would like to crop to (new_width X new_height):

import Image im = Image.open(<your image>) width, height = im.size   # Get dimensions  left = (width - new_width)/2 top = (height - new_height)/2 right = (width + new_width)/2 bottom = (height + new_height)/2  # Crop the center of the image im = im.crop((left, top, right, bottom)) 

This will break if you attempt to crop a small image larger, but I'm going to assume you won't be trying that (Or that you can catch that case and not crop the image).

like image 184
Chris Clarke Avatar answered Oct 16 '22 05:10

Chris Clarke