我希望在完成这篇文章之前能解决这个问题,但事情是这样的:
我有一个形状为 (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 = 数组([4460, 2718], dtype=int64) Bottom_right = 数组([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]
也等于0。
如何使用 array1
中的值填充 crop_array
,同时保留 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'
)
关于python - Numpy:从数组中选择所有行和列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41916626/