计算两个矩形之间的重叠区域 [英] Calculate overlapped area between two rectangles

查看:173
本文介绍了计算两个矩形之间的重叠区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算红色和蓝色矩形之间的重叠区域灰色区域".

I want to calculate the overlapped area "THE GRAY REGION" between red and blue rectangles.

每个矩形由其四个角坐标定义.重叠区域的结果单位是单位平方.

Each rectangle is defined by its four corner coordinates. The resulted unit of the overlapped area is unit square.

我无法想象该怎么办?

任何创意评论都将不胜感激.

Any creative comments would be appreciated.

推荐答案

这种交集很容易通过最大数的最小值"和最大数的最小值"的想法完成.要写出来,需要对矩形有一个特定的概念,并且为了使事情更清楚,我将使用一个namedtuple:

This type of intersection is easily done by the "min of the maxes" and "max of the mins" idea. To write it out one needs a specific notion for the rectangle, and, just to make things clear I'll use a namedtuple:

from collections import namedtuple
Rectangle = namedtuple('Rectangle', 'xmin ymin xmax ymax')

ra = Rectangle(3., 3., 5., 5.)
rb = Rectangle(1., 1., 4., 3.5)
# intersection here is (3, 3, 4, 3.5), or an area of 1*.5=.5

def area(a, b):  # returns None if rectangles don't intersect
    dx = min(a.xmax, b.xmax) - max(a.xmin, b.xmin)
    dy = min(a.ymax, b.ymax) - max(a.ymin, b.ymin)
    if (dx>=0) and (dy>=0):
        return dx*dy

print area(ra, rb)
#  0.5 

如果您不喜欢namedtuple表示法,则可以使用:

If you don't like the namedtuple notation, you could just use:

dx = max(a[0], b[0]) - min(a[2], b[2])

等,或您喜欢的任何符号.

etc, or whatever notation you prefer.

这篇关于计算两个矩形之间的重叠区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆