Reputation: 371
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?
Upvotes: 4
Views: 4449
Reputation: 10366
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
Upvotes: 4
Reputation: 13377
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
Upvotes: 1