我有兩個串列,第一個包含矩形中心的 x、y 坐標,第二個包含連接矩形的線的端點的 x、y、w、h 坐標。線的端點是 x1 = x, y1 = y, x2 = x w, y2 = y h。我試圖找到線的哪個端點最接近矩形的中心。我知道我需要使用畢達哥拉斯定理來計算端點與矩形中心之間的距離,但我在正確確定哪些端點最接近正確矩形的中心時遇到了問題。
互連的矩形
例子
在這個例子中 cx1, cy1 最近的端點應該是 x1, y1 和 cx2, cy2 最近的端點應該是 (x2, y2), (x3, y3) 和 (x5, y5)。其他矩形也是如此。藍線代表哪個紅點連接到哪個綠點。
distance = []
#masterStruc contains the x and y coordinates for the center of the rectangle
for z in range(len(masterStruc)):
cx = masterStruc[z][3]
cy = masterStruc[z][4]
#lineStruc contains the x, y, w, h coordinates for the end points of the line
for n in range(len(lineStruc)):
lx = lineStruc[n][0]
ly = lineStruc[n][1]
lw = lineStruc[n][2]
lh = lineStruc[n][3]
#Calculating the distances from the end points to the center of a rectangle
dist1 = int(math.sqrt((lx-cx)**2 (ly-cy)**2))
dist2 = int(math.sqrt((lx lw-cx)**2 (ly lh-cy)**2))
#Loop to compare which of the distances are closest to the center
for j in range(len(lineStruc)):
xx = lineStruc[n][0]
yy = lineStruc[n][1]
xw = lineStruc[n][2]
yh = lineStruc[n][3]
#Calculating the distances from the end points to the center of a rectangle
dist3 = int(math.sqrt((xx-cx)**2 (yy-cy)**2))
dist4 = int(math.sqrt((xx xw-cx)**2 (yy yh-cy)**2))
#Checking if the distance of the end points are closer
if(dist1 < dist4):
lx1 = lx
ly1 = ly
elif(dist1 < dist3):
lx1 = lx
ly1 = ly
elif(dist2 < dist4):
lx1 = lx lw
ly1 = ly lh
else:
lx1 = lx lw
ly1 = ly lh
#Storing the points of the closest end point and center of rectangle
distance.append([cx, cy, lx1, ly1])
uj5u.com熱心網友回復:
由于多個嵌套回圈,您的代碼很難閱讀和理解for。
一個好的做法是使用函式來構造代碼。任何可以用英文句子描述的操作都應該是它自己的功能。盡可能避免嵌套回圈;相反,將內部回圈封裝在一個函式中,并使用一個明確的名稱來描述這個函式的作用。
請注意,您實際上不需要使用math.sqrt,因為最小化距離等同于最小化平方距離。
def squared_distance(p1, p2):
(x1, y1) = p1
(x2, y2) = p2
return (x2 - x1)**2 (y2 - y1)**2
def get_closer_point(center, endpoints):
x, y, w, h = endpoints
p1 = (x, y)
p2 = (x w, y h)
if squared_distance(center, p1) <= squared_distance(center, p2):
return p1
else:
return p2
def get_closer_points(center_list, endpoints_list):
l = []
for c, e in zip(center_list, endpoints_list):
l.append(get_closer_point(c, e))
return l
# TESTING
centers = [(0,0), (37, 42), (18, 12)]
endpoints = [(1,0,0,1), (30,40,5,3), (20,20,-5,-5)]
closer_points = get_closer_points(centers, endpoints)
print('centers: ', centers)
print('endpoints: ', endpoints)
print('closer: ', closer_points)
# centers: [(0, 0), (37, 42), (18, 12)]
# endpoints: [(1, 0, 0, 1), (30, 40, 5, 3), (20, 20, -5, -5)]
# closer: [(1, 0), (35, 43), (15, 15)]
旁注:與其使用我們自己的函式來使用畢達哥拉斯定理計算兩點之間的距離,我們可以避免重新發明輪子并在 python 的標準庫中查找此函式。事實證明,確實有math.dist它可以做到這一點。因此,您可以 import math.dist,然后將squared_distance上面代碼中出現的每個 替換為math.dist。這很容易做到,因為我們已經封裝squared_distance為一個函式;如果我們每次需要時都明確地寫出畢達哥拉斯的公式,那會更煩人。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/441069.html
下一篇:從另一個陣列和組鍵中查找值
