Reputation: 3974
I have 2 arrays [nx1] that store xpixel (sample) and ypixel (line) coordinates, respectively. I have another array [nxn] storing an image. What I would like to do is create a third array which stores the pixel values from the image array at the given coordinates. I have this working with the following, but wonder if a built-in numpy function would be more efficient.
#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
A random generator determines the length of xsam and ylin along with the direction of travel through the image. It is therefore totally different with each iteration.
Upvotes: 3
Views: 206
Reputation: 414149
If image
is a numpy array and ylin
, xsam
are one dimensional:
newarr = image[ylin, xsam]
If ylin
, xsam
are two-dimensional with the second dimension being 1
e.g., ylin.shape == (n, 1)
then convert them to one-dimensional form first:
newarr = image[ylin.reshape(-1), xsam.reshape(-1)]
Upvotes: 3
Reputation: 5522
You can use advanced indexing:
In [1]: import numpy as np
In [2]: image = np.arange(16).reshape(4, 4)
In [3]: ylin = np.array([0, 3, 2, 2])
In [4]: xsam = np.array([2, 3, 0, 1])
In [5]: newarr = image[ylin, xsam]
In [6]: newarr
array([ 2, 15, 8, 9])
Upvotes: 3