Python 从两点之间的numpy数组中获取值
我有一个存储在2D numpy数组中的图像。我想从该数组中提取矩形中的所有像素值。矩形被定义为Python 从两点之间的numpy数组中获取值,python,arrays,numpy,Python,Arrays,Numpy,我有一个存储在2D numpy数组中的图像。我想从该数组中提取矩形中的所有像素值。矩形被定义为((x1,y1)、(x2,y2)),其中所有x和y都是自然数组索引 我可以使用嵌套的for循环来提取像素值,但是pythonic的方法是什么呢 只需使用切片即可。例如: In [3]: a = numpy.arange(20).reshape((4,5)) In [4]: a Out[4]: array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8,
((x1,y1)、(x2,y2))
,其中所有x和y都是自然数组索引
我可以使用嵌套的for循环来提取像素值,但是pythonic的方法是什么呢 只需使用切片即可。例如:
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]]
只需使用切片。例如:
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]]
看一看
看一看