使用PIL在旋转矩形的四个点上剪裁图像

3

我有一个旋转矩形的四个点的列表,格式如下:

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

我可以在PIL中使用以下方法进行剪裁:
img.crop((x1, y1, x2, y2))

但是这种方法无法处理旋转的矩形。为了澄清,我希望裁剪后的图像被旋转,使得裁剪区域成为一个非旋转的矩形。

我愿意使用openCV,尽管我想避免它,因为从PIL到openCV的图像转换需要时间,并且我将要重复执行大约100次这个过程。

1个回答

3
如果你从这张图片开始:

enter image description here

使用 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


非常感谢!我假设(200, 100)是输出图像的长度、宽度和高度。我想这些值可以通过x=((transform[2]-transform[0])**2+(transform[3]-transform[1])**2)**0.5和y=((transform[6]-transform[4])**2+(transform[7]-transform[5])**2)**0.5计算得出。 - Yetiowner
1
@Yetiowner 是的,我认为你说得对。我知道洋红色矩形的尺寸,因为我创建并旋转了它,但是我假设你可以像你一样准确地计算出长度。干得好! - Mark Setchell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接