簡體   English   中英

如何在numpy中旋轉索引數組?

[英]How to rotate an array of indices in numpy?

我有一個網格,它是一個形狀為(522, 476)的 numpy 數組。

然后我有另一個 numpy 數組,它是形狀(2, 3866)的單個 xy 點(網格的索引)的軌跡。

我使用np.rot90(grid)成功旋轉了網np.rot90(grid) 我的問題是如何以相同的方式旋轉軌跡,使各個 xy 點繼續與網格對齊。

如果您總是只想旋轉 90 度並且始終保持相同的方向(因此rot90沒有任何其他參數),您可以使用以下公式:

idx2 = np.array([[n.shape[0]-1-x[1], x[0]] for x in idx])

假設idx是您的索引數組 (2, 3866),而n是您想要索引的網格 (522, 476)。 它只是使用單次旋轉對元素的作用的知識,即將第一維切換到第二維,並使第二維從末尾開始計算為第一維。

您可以定義一個旋轉函數:

def rotate(origin, point, angle):
    """
    Rotate a point counterclockwise by a given angle around a given origin.

    The angle should be given in radians.
    """
    ox, oy = origin
    px, py = point

    qx = ox + math.cos(angle) * (px - ox) - math.sin(angle) * (py - oy)
    qy = oy + math.sin(angle) * (px - ox) + math.cos(angle) * (py - oy)
    return qx, qy

然后將此函數應用於軌跡的所有 (X,Y) 點。

origin = tuple(0, 0)
newTrajectory = []
for i in range(0:len(trajectory[0])):
    p = tuple(trajectory[i][0], trajectory[i][1])
    newP = rotate(origin, p, math.pi/2)
    row = [newP[0], newP[1]]
    newTrajectory.append(row)

最好的事物

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM