3

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.

2 Answers 2

3

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])
Sign up to request clarification or add additional context in comments.

Comments

3

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)]

1 Comment

You don't have to unravel ylin and xsam. If you don't do that, newarr will keep the same shape as ylin or xsam, which is quite useful (of course, the code from the OP returns a 1D newarr, but you could just .squeeze newarr at the end if you want that).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.