[英]Calculating volume of 3D model in Python
I have a nii file of a kidney which I upload in Python.我有一个肾脏的 nii 文件,我上传到 Python 中。 Is there any function in itk or vtk to calculate a volume of the kidney? itk或vtk中是否有任何function来计算肾脏的体积?
I share with you a solution with SimpleITK.我与您分享 SimpleITK 的解决方案。
You require a mask image of the kidney.您需要肾脏的蒙版图像。 The mask is a binary image with 1 values where the organ is and 0 values otherwise.掩码是一个二值图像,其中器官为 1 值,否则为 0 值。 If you don't have this already you can use 3DSlicer to segment the image, see here: 3DSlicer Segmentation .如果您还没有这个,您可以使用 3DSlicer 来分割图像,请参见此处: 3DSlicer Segmentation 。 After this you will have a kidney_mask.nii (or nrrd, default format) file.在此之后,您将拥有一个 nucleus_mask.nii(或 nrrd,默认格式)文件。
You can use the following script to compute the volume.您可以使用以下脚本来计算音量。
# script file image_volume.py
import argparse # argument parser
import numpy as np
import SimpleITK as sitk
def volume( mask_image ):
# Input:
# image = sitk.Image, mask or binary image (1 values where organ, 0 values otherwise)
# Output:
# vol = float, volume in mm3
space = mask_image.GetSpacing() # image spacing
voxel = np.prod(space) # voxel volume
img = sitk.GetArrayFromImage(mask_image)
vol = voxel*np.sum(img)
return vol
def main():
# Arguments details
parser = argparse.ArgumentParser(description='Compute volume of a mask image')
parser.add_argument("input", type=str,
help='Input file name')
# Parse arguments
args = parser.parse_args()
image_file = args.input
# Read the image
try:
image = sitk.ReadImage(image_file)
except:
print('Unable to read input image file.')
# Calculate the volume
print('Volume: {:f} [mm3]'.format(volume(image)))
print('Volume: {:f} [cm3]'.format(volume(image)/1000.0))
return
if __name__ == "__main__":
# execute only if run as a script
main()
Call the script as:将脚本称为:
python image_volume.py '/path/folder/kidney_mask.nii' python image_volume.py '/path/folder/kidney_mask.nii'
Here's how you can do it in just SimpleITK (the other answer uses numpy for the voxel count)这是您可以在 SimpleITK 中执行此操作的方法(另一个答案使用 numpy 进行体素计数)
import SimpleITK as sitk
stats = sitk.StatisticsImageFilter()
# img is a SimpleITK image
stats.Execute(img)
# get the number of voxels with label 1
nvoxels = stats.GetCount(1)
spacing = img.GetSpacing()
voxvol = spacing[0]*spacing[1]*spacing[2]
volume = nvoxels * voxvol
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.