python - Numpy:从数组中选择所有行和列

标签 python arrays numpy indexing

我希望在完成这篇文章之前能解决这个问题,但事情是这样的:

我有一个形状为 (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_leftbottom_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/

相关文章:

python - 使用 python 从文章中提取数据的多个正则表达式模式

python - 通过相机输入的实时性能消除运动模糊

python - 名称错误 : name 'sizes' is not defined-PYTHON

python - 如何在 basemap 顶部绘制不同密度的散点图

具有时间戳范围差异的对象数组上的javascript组

arrays - 如何将模拟结果的多个变量导出到csv?

c++ - 为什么此 c++ 代码在 Dev c++ 上运行而不在网站上运行?

python - 序列化大型 scipy 稀疏矩阵的最佳方法是什么?

python - 使用输出数组在 Python 中计算数组的积分

Python:如何读取列数不均匀的数据文件