python - 在python中计算两个旋转矩形的相交面积

标签 python

我有两个 2D 旋转矩形,定义为(中心 x,中心 y,高度,宽度)和旋转角度(0-360°)。我将如何计算这两个旋转矩形的相交面积。

最佳答案

此类任务是使用计算几何包解决的,例如Shapely :

import shapely.geometry
import shapely.affinity

class RotatedRect:
    def __init__(self, cx, cy, w, h, angle):
        self.cx = cx
        self.cy = cy
        self.w = w
        self.h = h
        self.angle = angle

    def get_contour(self):
        w = self.w
        h = self.h
        c = shapely.geometry.box(-w/2.0, -h/2.0, w/2.0, h/2.0)
        rc = shapely.affinity.rotate(c, self.angle)
        return shapely.affinity.translate(rc, self.cx, self.cy)

    def intersection(self, other):
        return self.get_contour().intersection(other.get_contour())


r1 = RotatedRect(10, 15, 15, 10, 30)
r2 = RotatedRect(15, 15, 20, 10, 0)

from matplotlib import pyplot
from descartes import PolygonPatch

fig = pyplot.figure(1, figsize=(10, 4))
ax = fig.add_subplot(121)
ax.set_xlim(0, 30)
ax.set_ylim(0, 30)

ax.add_patch(PolygonPatch(r1.get_contour(), fc='#990000', alpha=0.7))
ax.add_patch(PolygonPatch(r2.get_contour(), fc='#000099', alpha=0.7))
ax.add_patch(PolygonPatch(r1.intersection(r2), fc='#009900', alpha=1))

pyplot.show()

enter image description here

关于python - 在python中计算两个旋转矩形的相交面积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44797713/

相关文章:

python - 如何将字典列表转换为....?

python - 替换txt文件中的整行

python - TensorFlow 2.0 dataset.__iter__() 仅在启用即时执行时才受支持

python - 使用 numpy 数组函数更新元素

python - Firebase .validate 无法按预期使用 $location

Python:将 JSON 添加到现有 JSON

python - 如何检测用于将显微镜图像旋转对准模板的良好特征

python - 如何使用 Python 查询作为 Mongodb 中列表字段的列表中命中元素的计数?

python - 如何根据相同的虚拟向量对两个 Pandas 数据帧进行编码?

python - 获取 np.linalg.svd 的奇异值作为矩阵