[英]Finding the slices from a list of coordinates in a numpy
我想從多維 numpy 中的坐標列表中檢索切片列表。
我正在做的是以下(示例)。
首先,我聲明我的基本數組:
base = np.zeros((8, 8, 4))
帶有坐標列表:
coord = [slice(0, 1, None), slice(0, None, None)]
其次,我在 numpy 中創建了一個“掩碼”:
base[coord] = -1
然后,我提取該區域的切片:
np.argwhere(base == -1)
我遇到的問題是我不想修改 numpy 以提取坐標,當然副本不是可能的解決方案。 這樣做的方法是什么,或者我應該為獲得切片做哪些修改?
您可以使用范圍而不是切片創建坐標數組np.meshgrid
:
import numpy as np
base = np.zeros((8, 8, 4))
coord = [range(0, 1), range(0, base.shape[1])]
coords_array = np.stack(np.meshgrid(*coord, indexing='ij'), -1).reshape(-1, len(coords))
print(coords_array)
# [[0 0]
# [0 1]
# [0 2]
# [0 3]
# [0 4]
# [0 5]
# [0 6]
# [0 7]]
嘗試這個:
import numpy as np
base = np.zeros((8, 8, 4))
coord = [slice(0, 1, None), slice(0, None, None)]
all_coords = np.argwhere(base == base).reshape(*base.shape,base.ndim) # (8,8,4,3)
print(all_coords[coord].reshape(-1,base.ndim))
Output:
[[0 0 0]
[0 0 1]
[0 0 2]
[0 0 3]
[0 1 0]
[0 1 1]
[0 1 2]
[0 1 3]
[0 2 0]
[0 2 1]
[0 2 2]
[0 2 3]
[0 3 0]
[0 3 1]
[0 3 2]
[0 3 3]
[0 4 0]
[0 4 1]
[0 4 2]
[0 4 3]
[0 5 0]
[0 5 1]
[0 5 2]
[0 5 3]
[0 6 0]
[0 6 1]
[0 6 2]
[0 6 3]
[0 7 0]
[0 7 1]
[0 7 2]
[0 7 3]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.