使用两个左下角和右上角检查python中的两个矩形是否重叠

2024-09-29 23:15:59 发布

您现在位置:Python中文网/ 问答频道 /正文

class Point:

    def __init__(self, xcoord=0, ycoord=0):
        self.x = xcoord
        self.y = ycoord

class Rectangle:
    def __init__(self, bottom_left, top_right, colour):
        self.bottom_left = bottom_left
        self.top_right = top_right
        self.colour = colour

    def intersects(self, other):

我试着看两个矩形是否相交于右上角和左下角,但是当我做这个函数时:

def intersects(self, other):
    return self.top_right.x>=other.top_right.x>=self.bottom_left.x and self.top_right.x>=other.bottom_left.x>=self.bottom_left.x and self.top_right.y>=other.top_right.y>=self.bottom_left.y and self.top_right.x>=other.bottom_left.x>=self.bottom_left.x

当输入以下内容时,函数将返回false:

r1=Rectangle(Point(1,1), Point(2,2), 'blue')
r3=Rectangle(Point(1.5,0), Point(1.7,3), 'red')
r1.intersects(r3)

进入弹壳。


Tags: andselfrightinittopdefleftclass
3条回答

我最近遇到了这个问题,今天遇到了命名元组,所以我想试试:

from collections import namedtuple

RECT_NAMEDTUPLE = namedtuple('RECT_NAMEDTUPLE', 'x1 x2 y1 y2')

Rect1 = RECT_NAMEDTUPLE(10,100,40,80)
Rect2 = RECT_NAMEDTUPLE(20,210,10,60)

def overlap(rec1, rec2):
  if (Rect2.x2 > Rect1.x1 and Rect2.x2 < Rect1.x2) or \
     (Rect2.x1 > Rect1.x1 and Rect2.x1 < Rect1.x2):
    x_match = True
  else:
    x_match = False
  if (Rect2.y2 > Rect1.y1 and Rect2.y2 < Rect1.y2) or \
     (Rect2.y1 > Rect1.y1 and Rect2.y1 < Rect1.y2):
    y_match = True
  else:
    y_match = False
  if x_match and y_match:
    return True
  else:
    return False

print ("Overlap found?", overlap(Rect1, Rect2))

Overlap found? True

也可以使用shapely中的多边形(例如具有[x0,y0,x1,y1]的矩形)

from shapely.geometry import Polygon
import numpy as np

rect1=np.array([0  ,0 , 4,  4])
rect2=np.array([1 , 1 , 5 , 5])

def overlap(rect1,rect2):
    try:
        p1 = Polygon([(rect1[0],rect1[1]), (rect1[1],rect1[1]),(rect1[2],rect1[3]),(rect1[2],rect1[1])])
        p2 = Polygon([(rect2[0],rect2[1]), (rect2[1],rect2[1]),(rect2[2],rect2[3]),(rect2[2],rect2[1])])
        return(p1.intersects(p2))
    except:
        return True

print(overlap(rect1,rect2))

可以使用Separating Axis Theorem的简单版本来测试交集。如果矩形不相交,则至少一个右侧将位于另一个矩形左侧的左侧(即,它将是一个分离轴),反之亦然,或者一个顶部将位于另一个矩形的底部下方,反之亦然。

因此,更改测试以检查它们是否不相交:

def intersects(self, other):
    return not (self.top_right.x < other.bottom_left.x or self.bottom_left.x > other.top_right.x or self.top_right.y < other.bottom_left.y or self.bottom_left.y > other.top_right.y)

这段代码假设“top”的y值大于“bottom”(y在屏幕下方减小),因为这就是示例的工作方式。如果你使用的是另一个约定,那么你只需要翻转y比较的符号。

相关问题 更多 >

    热门问题