4

I have a 3D array a a is an numpy array of shape of (512, 512, 133)) which contains non zero values in a certain area.

I would like to calculate the volume of non zero area in this 3D numpy array.

If I know the pixel spacing (0.7609, 0.7609, 0.5132), how the actual volume can be found in python?

1
  • The volume would simply be the number of non-zero entries or am I misunderstanding you? Commented Aug 30, 2019 at 8:30

2 Answers 2

4

The volume of your 3D numpy array equals to the amount of non-zero elements times the volume a pixels takes.

To get the amount of non-zero elements in a numpy array.

import numpy as np
units = np.count_nonzero([[[ 0.,  0.],
                           [ 2.,  0.],
                           [ 0.,  3.]],

                          [[ 0.,  0.],
                           [ 0.,  5.],
                           [ 7.,  0.]]])
# will output 4

If you know the spacing s between two pixels the volume of a pixel is calculated as the volume of a square (pixel volume) times the amount of pixels you previously determined.

volume = units * pow(s, 3)

Update:

As your spacings (s1, s2, s3) are not equidistant in your 3 dimensions, the volume will change to

volume = units * s1 * s2 * s3
# volume = 4 * 0.7609 * 0.7609 * 0.5132
Sign up to request clarification or add additional context in comments.

Comments

1

Try this one:

import numpy as np
import random
#Not sure how exactly you define input, this is how I approached it:
matrix=np.zeros((1000, 1000, 1000))

for i in range(1000):
    matrix[random.randint(0, 999), random.randint(0, 999), random.randint(0, 999)] = random.randint(0, 10)

x=np.nonzero(matrix) #returns tuple of all non-zero elements (in format [X, Y, Z])
#and the final result - number of non zero elements - based on 1 coordinate (as len(X)=len(y)=len(Z)

print(len(x[0])) #in my case returns => 924

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.