我有一个图像存储在 2D numpy 数组中。我想从该数组中提取矩形中的所有像素值。该矩形定义为((x1,y1),(x2,y2))
,其中所有 x 和 y 自然都是数组索引。
我可以使用嵌套的 for 循环提取像素值,但是执行此操作的 Python 方法是什么?
最佳答案
只需使用切片即可。例如:
In [3]: a = numpy.arange(20).reshape((4,5))
In [4]: a
Out[4]:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
In [5]: a[2:4, 3:5]
Out[5]:
array([[13, 14],
[18, 19]])
一般来说,您可以用切片替换索引,其中切片的形式为 start:stop 或可选的 start:stop:step 并且允许使用变量:
In [6]: x=2 ; print a[x-1:x+1, :]
[[ 5 6 7 8 9]
[10 11 12 13 14]]
关于python - 从两点之间的 numpy 数组获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22081288/