[英]Numpy: Select all rows and columns from an array
我希望在完成這篇文章之前能解決這個問題,但是事情就這樣了:
我有一個形狀為(4808L,5135L)的數組array1
,我正在嘗試選擇該數組的矩形子集。 具體來說,我試圖選擇4460:4807
行中的所有值以及2718:2967
列中的所有值。
首先,我創建一個與array1
形狀相同的蒙版,例如:
mask = np.zeros(array1.shape[:2], dtype = "uint8")
mask[array1== 399] = 255
然后我試圖找到mask = 255
的點的索引:
true_points = np.argwhere(mask)
top_left = true_points.min(axis=0)
# take the largest points and use them as the bottom right of your crop
bottom_right = true_points.max(axis=0)
cmask = mask[top_left[0]:bottom_right[0]+1, top_left[1]:bottom_right[1]+1]
其中:top_left = array([4460,2718],dtype = int64)bottom_right = array([4807,2967],dtype = int64)
cmask
看起來正確。 然后使用top_left
和bottom_right
我嘗試使用以下方法對array1
進行子集化:
crop_array = array1[top_left[0]:bottom_right[0]+1, top_left[1]:bottom_right[1]+1]
這導致crop_array
具有相同的形狀cmask
,但值不正確填充。 由於cmask[0][0] = 0
所以我希望crop_array[0][0]
也等於零。
我如何poulate crop_array
與值從array1
,同時保持結構cmask
?
提前致謝。
如果我正確理解了您的問題,那么您正在尋找.copy()方法。 匹配索引和變量的示例:
import numpy as np
array1 = np.random.rand(4808,5135)
crop_array = array1[4417:,2718:2967].copy()
assert np.all(np.equal(array1[4417:,2718:2967], crop_array)) == True, (
'Equality Failed'
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.