Python 使用数组的Numpy索引
我有两个数组[nx1],分别存储xpixel(sample)和ypixel(line)坐标。我有另一个存储图像的数组[nxn]。我想做的是创建第三个数组,它在给定坐标处存储图像数组中的像素值。我将此功能与以下功能结合使用,但不知道内置的numpy函数是否会更有效Python 使用数组的Numpy索引,python,numpy,scipy,Python,Numpy,Scipy,我有两个数组[nx1],分别存储xpixel(sample)和ypixel(line)坐标。我有另一个存储图像的数组[nxn]。我想做的是创建第三个数组,它在给定坐标处存储图像数组中的像素值。我将此功能与以下功能结合使用,但不知道内置的numpy函数是否会更有效 #Create an empty array to store the values from the image. newarr = numpy.zeros(len(xsam)) #Iterate by index and pull
#Create an empty array to store the values from the image.
newarr = numpy.zeros(len(xsam))
#Iterate by index and pull the value from the image.
#xsam and ylin are the line and sample numbers.
for x in range(len(newarr)):
newarr[x] = image[ylin[x]][xsam[x]]
print newarr
随机生成器确定xsam和ylin的长度以及通过图像的行进方向。因此,每次迭代都完全不同。您可以使用:
如果
image
是一个numpy数组并且ylin
,xsam
是一维的:
newarr = image[ylin, xsam]
如果ylin
,xsam
是二维的,第二个维度是1
,例如ylin.shape==(n,1)
,那么首先将它们转换为一维形式:
newarr = image[ylin.reshape(-1), xsam.reshape(-1)]
您不必解开
ylin
和xsam
。如果不这样做,newarr
将保持与ylin
或xsam
相同的形状,这是非常有用的(当然,OP中的代码返回1Dnewarr
,但如果需要,您可以在末尾挤压
)。
newarr = image[ylin.reshape(-1), xsam.reshape(-1)]