Python-判断矩形与多边形相交

判断矩形与不规则多边形相交。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
borderPoints = [(100, 100), (250, 100), (250, 250), (100, 250)]
def rectInRegion(x1, y1, x2 ,y2):
global borderPoints
rectPoints = [(x1, y1), (x1, y2), (x2, y1), (x2, y2)]
pointsLen = len(borderPoints)
for x, y in rectPoints:
winding = 0
for i in range(pointsLen):
p1x, p1y = borderPoints[i]
p2x, p2y = borderPoints[(i + 1) % pointsLen]
cv2.rectangle(canvas, (p1x, p1y), (p2x, p2y), (255, 0, 0), 2)
if p1y <= y:
if p2y > y:
if ((p2x - p1x) * (y - p1y) - (x - p1x) * (p2y - p1y)) > 0:
winding += 1
else:
if p2y <= y:
if ((p2x - p1x) * (y - p1y) - (x - p1x) * (p2y - p1y)) < 0:
winding -= 1
if winding != 0:
return True
return False