Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crop an image in PIL using the 4 points of a rotated rectangle

I have a list of four points of a rotated rectangle in the form of:

points = [[x1, y1], [x2, y2], [x3, y3], [x4, y4]]

I can crop in PIL using:

img.crop((x1, y1, x2, y2))

But this doesn't work with a rotated rectangle. Just to clarify I want the resulting cropped image to be rotated so the cropped area becomes a non-rotated rectangle.

I am willing to use openCV, although would like to avoid it as the conversion of an image from PIL to openCV takes time, and I will be itterating through this process about 100 times.

like image 630
Yetiowner Avatar asked Oct 27 '25 13:10

Yetiowner


1 Answers

If you start with this image:

enter image description here

You can do it like this using a QuadTransform:

#!/usr/bin/env python3

from PIL import Image, ImageTransform

# Open starting image and ensure RGB
im = Image.open('a.png').convert('RGB')

# Define 8-tuple with x,y coordinates of top-left, bottom-left, bottom-right and top-right corners and apply
transform=[31,146,88,226,252,112,195,31]
result = im.transform((200,100), ImageTransform.QuadTransform(transform))

# Save the result
result.save('result.png')

![enter image description here

like image 92
Mark Setchell Avatar answered Oct 29 '25 03:10

Mark Setchell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!