Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set coordinates when cropping an image with PIL?

I don't know how to set the coordinates to crop an image in PILs crop():

from PIL import Image
img = Image.open("Supernatural.xlsxscreenshot.png")
img2 = img.crop((0, 0, 201, 335))
img2.save("img2.jpg")

I tried with gThumb to get coordinates, but if I take an area which I would like to crop, I can only find position 194 336. Could someone help me please?

This is my picture:

enter image description here

I wish to crop to this:

enter image description here

like image 559
Anna K Avatar asked Sep 10 '16 08:09

Anna K


People also ask

How do I crop an image 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 I crop an image to a specific size in Python?

Use resize() to resize the whole image instead of cutting out a part of the image, and use putalpha() to create a transparent image by cutting out a shape other than a rectangle (such as a circle). Use slicing to crop the image represented by the NumPy array ndarray . Import Image from PIL and open the target image.


2 Answers

How to set the coordinates to crop

In the line:

img2 = img.crop((0, 0, 201, 335))

the first two numbers define the top-left coordinates of the outtake (x,y), while the last two define the right-bottom coordinates of the outtake.

Cropping your image

To crop your image like you show, I found the following coordinates: top-left: (200, 330), and right-bottom: (730, 606). Subsequently, I cropped your image with:

img2 = img.crop((200, 330, 730, 606))

enter image description here

with the result:

enter image description here

like image 169
Jacob Vlijm Avatar answered Oct 02 '22 15:10

Jacob Vlijm


@Jacob Vlijm thankx for the great explanation.

But, those who are in hurry or are stupid like me - here is an abstraction-:)

python pillow coordinate system abstraction

like image 27
YoBro_29 Avatar answered Oct 02 '22 16:10

YoBro_29