0

I have a vtkVolume and I have to check all the voxels to keep the coordinates of the points with a certain value in some lists. For example, if the possible values ​​are 3 (for example 0, 1, 2), I have to check all the voxels of the volume and keep in 3 different lists the coordinates of the points that have value 0, those that have value 1 and those that have value 2.

What are the most efficient ways to do this with numpy? I tried to iterate over the whole volume with shape (512, 512, 359) with some classic nested for loops but it takes too long.

3
  • 1
    There isn't an efficient way to iterate, at least not with Python code. numpy compiled methods can iterate efficiently, but you are limited to the provided methods. There are tools like numba and cython for writing your own compiled code. But for iteration in Python, lists, even nested lists, are better than arrays. You need to read some more numpy basics. Commented Nov 25, 2020 at 1:24
  • In fact, I was asking for some numpy built-in method, because I used numpy.place() to replace values ​​given a condition and it is very fast. To do this it has to iterate over the entire volume, which is just what I'm trying to do efficiently. Thanks for the advice Commented Nov 25, 2020 at 1:32
  • See also: stackoverflow.com/questions/16094563/… Commented Dec 3, 2020 at 16:23

1 Answer 1

2

Super simple:

a = np.random.randint(3, size=(3,3,3))

# array([[[0, 2, 1],
#         [1, 1, 0],
#         [1, 0, 2]],
# 
#        [[2, 1, 2],
#         [2, 0, 2],
#         [1, 0, 1]],
# 
#        [[0, 2, 2],
#         [0, 0, 1],
#         [2, 2, 2]]])

i0 = np.where(a==0)

# (array([0, 0, 0, 1, 1, 2, 2, 2], dtype=int64),
#  array([0, 1, 2, 1, 2, 0, 1, 1], dtype=int64),
#  array([0, 2, 1, 1, 1, 0, 0, 1], dtype=int64))

a[i0[0], i0[1], i0[2]]

# array([0, 0, 0, 0, 0, 0, 0, 0])

same for other values:

i1 = np.where(a==1)
i2 = np.where(a==2)
Sign up to request clarification or add additional context in comments.

3 Comments

I tried this solution but I need the coordinates of the points with that value, not the value itself. In this case, for label=0 I have to get a list with the coordinates of the points in the array with value 0
Yes they are in i0, i1, i2 as I've shown. The last line a[i0[0], i0[1], i0[2]] is just to illustrate they actually are what you want.
You're right, my bad. It is perfectly what I need, thank you very much!

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.