We can crop an area of an image. Let’s say that I would like to extract the tattoo on the girl’s back:
Pillow uses a coordinate system in which the coordinates 0.0 are in the upper left corner. The crop() method takes a four element tuple (left, upper, right, lower) to specify the top left and the bottom right corner of the rectangle. To find out the exact numbers I need to provide, I can use a program like Microsoft Paint that will tell me the location of the tattoo:
I’ve positioned the mouse on the location on the image where I want to be the top left corner of the rectangle. Notice the numbers in the bottom left corner of the image (555,344):
These are the first two coordinates. To get the other two coordinates, I would move my mouse to the bottom right of the rectangle. In my case, the bottom right coordinates are 598,380.
I will now create a tuple called area that contains the coordinates and then pass the tuple to the crop() method:
area = (555,344,598,380) cropped_img = img.crop(area)
The function crop takes a single parameter – the tuple that contains the coordinates.
So the whole code looks like this:
from PIL import Image img = Image.open('handsome.jpg') area = (555, 344, 598, 380) cropped_img = img.crop(area) cropped_img.show()
This is the result: