如何在Python中获取多边形内的网格点坐标? [英] How to get the coordinates of grid points inside a polygon in Python?
问题描述
我想输入一个多边形的4个顶点的坐标,指定点数以划分多边形的边缘(等分),目标是生成一个矩阵,该矩阵具有多边形内部的网格点的坐标
I want to input the coordinates of 4 vertices of a polygon, specify the number of points to divide the polygon's edges (in equal segments), and the goal is to generate a matrix with the coordinates of the grid points inside the polygon.
以下图片可能更好地说明了我的目标:
The following picture might explain better my goal:
因此,在那种情况下,我将输入点(P)的坐标并指定我希望网格为3 x2.输出将是一个3 x 2矩阵,网格为(x,y)点(N).
So in that case I would input the coordinates of the points (P) and specify that I want grid to be 3 by 2. The output would be a 3 by 2 matrix with the coordinates (x,y) of the grid points (N).
我已经搜索了很多东西,但是仍然找不到做到这一点的方法,老实说,我对Python一点都不了解.我发现使用numpy的meshgrid结合matplotlib.path的contains_points可以在多边形内部创建网格,但是我不知道如何获取网格点的坐标.我看到身材匀称的人经常在这样的问题中使用,但再次,我没有经验,因此可以提供一些帮助!
I have searched a lot but still couldn't find a way to do this, and honestly I am not at all experienced with Python. I found something using numpy's meshgrid in combination with matplotlib.path's contains_points to create a grid inside a polygon but I have no idea how to get the grid point's coordinates. I saw shapely being used a lot in problems like this but again, I'm not experience in this so some help would be appreciated!
谢谢大家!
推荐答案
为解释该方法,我们分三个步骤:
To explain the approach, we have three steps:
- 找到4边形各边的刻度线
- 找到网格线
- 找到网格线的交点
def det(a, b):
return a[0] * b[1] - a[1] * b[0]
ticks = []
A = (1, 2) # wlog., suppose the polygon is ABCD;
B = (3, 2)
C = (3, 4)
D = (1, 4)
polygon = [A, B, C, D]
n = 3 # number of parts on each side of the grid
# we first find ticks on each side of the polygon
for j in range(4): # because we are talking about 4-gons
temp_ticks = []
for i in range(n-1):
t = (i+1)*(1/n)
Ex = polygon[j][0] * (1-t) + polygon[(j+1) % 4][0] * t
Ey = polygon[j][1] * (1-t) + polygon[(j+1) % 4][1] * t
temp_ticks.append((Ex, Ey))
if j < 2:
ticks.append(temp_ticks)
else: # because you are moving backward in this part
temp_ticks.reverse()
ticks.append(temp_ticks)
# then we find lines of the grid
h_lines = []
v_lines = []
for i in range(n-1):
h_lines.append((ticks[0][i], ticks[2][i]))
v_lines.append((ticks[1][i], ticks[3][i]))
# then we find the intersection of grid lines
for i in range(len(h_lines)):
for j in range(len(v_lines)):
line1 = h_lines[i]
line2 = v_lines[j]
xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])
ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1])
div = det(xdiff, ydiff)
if div == 0:
raise Exception('lines do not intersect')
d = (det(*line1), det(*line2))
x = det(d, xdiff) / div
y = det(d, ydiff) / div
print(x,y) # this is an intersection point that you want
Note: the part of the code for finding the intersection of lines are from here
这篇关于如何在Python中获取多边形内的网格点坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!