我的目的主要是利用 nibabel 这个库来处理一些 NIFTI 格式的 医学方面的数据。
官方的网址如下:
https://nipy.org/nibabel/nibabel_images.html#the-image-object
首先, 自然是安装库, 然后我们使用 load 函数来读取一个 nii.gz格式的文件,
它 return 的是一个 <class 'nibabel.nifti1.Nifti1Image'> 类型的 object
import nibabel as nib
img = nib.load(example_file)
关于 这个return 回来的数据类型, 我们要知道如下的三点:
(n维数组, 代表图像, 仿射变换 , meta_data)
A nibabel image object is the association of three things:
-
an N-D array containing the image data;
-
a (4, 4) affine matrix mapping array coordinates to coordinates in some RAS+ world coordinate space (Coordinate systems and affines);
-
image metadata in the form of a header.
# demo
简单的读取, 查看return 的 object 的类型 和 shape
if __name__ == '__main__':
demo_img, demo_seg = load_case(cid=123)
print(type(demo_img))
print(demo_img.shape
--------------- output ----------
<class 'nibabel.nifti1.Nifti1Image'>
(61, 512, 512)
# 使用 get_fdata , 就可以转为float 为 dtype 的 ndarray类型的 object
hu_data = demo_img.get_fdata()
print(hu_data.shape)
print(type(hu_data))
print(hu_data.dtype)
——————————————--------output-- - - -----------
<class 'nibabel.nifti1.Nifti1Image'>
(61, 512, 512)
<class 'numpy.ndarray'>
float64
# 你可能也见过这个函数 get_data 缺少了一个‘ f ’ ,
I'm working with Nibabel to read some .nii files.
I came across different examples and some of them use get_data() function
while some of them use get_fdata() function.
I could not find what the difference is in their documentation (nibabel manuel).
Can anyone explain?
在这里可以找到 https://nipy.org/nibabel/reference/nibabel.dataobj_images.html
(也就是get_data 和 get_fdata 的一些区别)
二者的一些说明如下:
get_data(caching='fill')
Return image data from image with any necessary scaling applied
get_fdata(caching='fill', dtype=)
Return floating point image data with necessary scaling applied
简单的来说, 一个是返回原数据, 一个则是返回浮点数。
就是这么点区别
不过有一点需要注意 , 这个get_data 函数要被取缔了:
We recommend you use the get_fdata method instead of the get_data method,
because it is easier to predict the return data type.
We will deprecate the get_data method around April 2018,
and remove it around April 2020.
If you don’t care about the predictability of the return data type,
and you want the minimum possible data size in memory,
you can replicate the array
that would be returned by img.get_data() by using np.asanyarray(img.dataobj).