我正在製作一個程序,可以找到圖像上兩點之間的路徑(很快就會成為視訊幀)。我所做的是使用多邊形物件來識別路徑之間的障礙物,並使用該多邊形物件根據需要繞過。我的程式碼如下:
simplepoint = tuple[int, int] def getpolygonsinway(start: simplepoint, end: simplepoint, polygons: list[polygon]) -> list[polygon]: line = linestring([start, end]) polygonsinway = [polygon for polygon in polygons if line.crosses(polygon)] # make sure line.crosses() doesnt return true if the starting point is on the polygon return polygonsinway def getpaths(start: simplepoint, end: simplepoint, polygons: list[polygon], prev_points: list[simplepoint] = []) -> list[list[simplepoint]]: polygonsinway = getpolygonsinway(start, end, polygons) if not polygonsinway: return [[start, end]] closestpolygon = closestpolygontopoint(start, polygons) xyvalsold = closestpolygon.exterior.xy xyvals = [] for i in range(len(xyvalsold[0])): xyvals.append((xyvalsold[0][i], xyvalsold[1][i])) xyvals = list(set(xyvals)) # remove duplicates polxvals = [val[0] for val in xyvals] polyvals = [val[1] for val in xyvals] okpoints = [] for i in range(len(polxvals)): if start == (polxvals[i], polyvals[i]): continue if int(polxvals[i]) != polxvals[i] or int(polyvals[i]) != polyvals[i]: continue if (int(polxvals[i]), int(polyvals[i])) in prev_points: continue if closestpolygon not in getpolygonsinway(start, (polxvals[i], polyvals[i]), polygons): #and closestpolygon not in getpolygonsinway((polxvals[i], polyvals[i]), end, polygons): okpoints.append((int(polxvals[i]), int(polyvals[i]))) paths = [[start] for _ in range(len(okpoints))] for i in range(len(okpoints)): point = (okpoints[i][0], okpoints[i][1]) paths[i].extend(getshortestpath(getpaths(point, end, polygons, prev_points + [point]), point, end)) return paths
目前,我使用的唯一障礙是簡單的形狀,例如矩形、正方形、圓形等,一旦一切正常,我將改用影片。當兩個部分是矩形的對角線時,函數 getpolygonsinway
中的列表理解中的 line.crosses(polygon)
傳回 false 時,會出現問題。我已經查看了文檔,但我不知道用什麼來確保我正確地捕獲這個案例,所以我在這裡問了這個問題。
編輯:根據要求,範例多邊形、起點和終點如下:
polygon = Polygon([[411, 182], [411, 335], [210, 335], [210, 182]]) start = (440, 35) end = (90, 600)
使用上面的程式碼,執行 getshortestpath(getpaths(start, end, polygons, []))
後得到以下路徑:
[(440, 35), (411, 182), (210, 335), (90, 600)]
#我找到了line.within(polygon)
方法,該方法檢查該線是否位於傳遞的多邊形內部。我不知道為什麼我以前沒有看到它,但現在我看到了。透過在列表理解 if 條件中執行 line.crosses(polygon) 或 line.within(polygon)
,我設法獲得了圍繞矩形的路徑。我現在將使用其他基本形狀來測試它,然後無限地測試它的用途。
以上是檢查一條線是否以任何方式穿過多邊形的詳細內容。更多資訊請關注PHP中文網其他相關文章!