这种类型的交集很容易通过“最大值的最小值”和“最小值的最大值”的想法来完成。为了将其写出来,需要对矩形有一个特定的概念,并且,为了使事情清楚,我将使用一个命名元组:
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
如果您不喜欢命名元组表示法,您可以使用:
dx = max(a[0], b[0]) - min(a[2], b[2])
等等,或者任何你喜欢的符号。