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.

Gibser
  • 197
  • 8
  • 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. – hpaulj Nov 25 '20 at 01: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 – Gibser Nov 25 '20 at 01:32
  • See also: https://stackoverflow.com/questions/16094563/numpy-get-index-where-value-is-true – NoDataDumpNoContribution Dec 03 '20 at 16:23

1 Answers1

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)
Julien
  • 13,986
  • 5
  • 29
  • 53
  • 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 – Gibser Nov 25 '20 at 01:11
  • 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. – Julien Nov 25 '20 at 01:17
  • You're right, my bad. It is perfectly what I need, thank you very much! – Gibser Nov 25 '20 at 01:20