2

So I have image data which I am iterating through in order to find the pixel which have useful data in them, I then need to find these coordinates subject to a conditional statement and then put these into an array or DataFrame. The code I have so far is:

pix_coor = np.empty((0,2))

for (x,y), value in np.ndenumerate(data_int):
  if value >= sigma3:
    pix_coor.append([x,y])

where data is just an image array (129,129). All the pixels that have a value larger than sigma3 are useful and the other ones I dont need.

Creating an empty array works fine but when I append this it doesn't seem to work, I need to end up with an array which has two columns of x and y values for the useful pixels. Any ideas?

2 Answers 2

2

You could simply use np.argwhere for a vectorized solution -

pix_coor = np.argwhere(data_int >= sigma3)
Sign up to request clarification or add additional context in comments.

Comments

2

In numpy, array.append is not an inplace operation, instead it copies the entire array into newly allocated memory (big enough to hold it along with the new values), and returns the new array. Therefore it should be used as such:

  new_arr = arr.append(values)

Obviously, this is not an efficient way to add elements one by one.

You should use probably a regular python list for this.

Alternatively, pre allocate the numpy array with all values and then resize it:

 pix_coor = np.empty((data_int.size, 2), int)
 c = 0
 for (x, y), value in np.ndenumerate(data_int):
     if value >= sigma3:
         pix_coor[c] = (x, y)
         c += 1
 numpy.resize(pix_coor, (c, 2))

Note that I used np.empty((data_int.size, 2), int), since your coordinates are integral, while numpy defaults to floats.

Comments

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.