【Python】实现MATLAB中计算两个矩形相交面积的rectint函数

1 rectint函数

A 和 B 是一个思维向量 [x,y,width,height]

area = rectint(A,B)

在这里插入图片描述

2 Python实现


class Rectangle:
    def __init__(self, x, y,w,h):
      self.x = x
      self.y = y
      self.width = w
      self.height = h
ra = Rectangle(3., 3., 5., 5.)
rb = Rectangle(1., 1., 4., 4.)
# intersection here is (3, 3, 4, 3.5), or an area of 1*.5=.5

def calc_area(rect1, rect2):
    xl1, yb1, xr1, yt1 = rect1.x,rect1.y,rect1.x+rect1.width,rect1.y+rect1.height 
    # (xl1, yb1)为矩形左下角坐标, (xr1, yt1)为右上角坐标
    xl2, yb2, xr2, yt2 = rect2.x,rect2.y,rect2.x+rect2.width,rect2.y+rect2.height 
    # (xl2, yb2)为矩形左下角坐标, (xr2, yt2)为右上角坐标
    xmin = max(xl1, xl2)
    ymin = max(yb1, yb2)
    xmax = min(xr1, xr2)
    ymax = min(yt1, yt2)
    width = xmax - xmin
    height = ymax - ymin
    if width <= 0 or height <= 0:
        return 0
    cross_square = width * height
    return cross_square

print(area(ra, rb))
# 4.0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Better Bench

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值