程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python notes: open NII format (nibabel Library)

編輯:Python

1 nii Format Introduction

 1.0 Analyze Format

In explanation NII(NIFTI,neuroimaging information technology initiative) Before the format , We need to know first Analyze Format .

every last Analyze The format data contains two files : With binary image information .img, Header file containing image metadata .hdr

however ,Analyze The header file of does not really reflect metadata ( For example, there is no direction information ,eg On the left or on the right ), therefore NIFTI Format file came into being

1.1 Part of the

nii Format (nifti Format extension ) It was invented for multidimensional neuroimaging . One nii The format mainly consists of three parts :hdr, ext, img

  • hdr
    • header, Data header
    • The length of this part of data is fixed , Of course, different versions may specify different lengths , But the same version of multiple nii The files are the same .
    • header The information contained in the :
      • -- dimension , At least three dimensions ,x,y,z, It's in millimeters . There may also be a fourth dimension , It's time . This part mainly stores four numbers .
      • --voxel size( Voxel size ): In millimeters x,y,z size .
      • -- data type , It's usually int16, This precision is not enough , Best use double type .
      • Form And the transformation matrix , every last Form All correspond to a transformation matrix .
        •   The transformation matrix can easily distinguish the left and right of the image , The function is to index voxels (i,j,k) Convert to spatial location (x,y,z).
        • The specific method of use is to multiply the transformation matrix by a containing (i,j,k) Matrix , You can get a containing (x,y,z) Matrix .
          •   Voxels can be compared to pixels in a two-dimensional image . Voxels are fixed resolution 3D raster maps
  • ext
    • extension
    • It is the part that can define data at will , You can use it yourself .
  • img
    • image
    • Store 3D perhaps 4D Image data
    • .hdr and .img You can use a single file .nii Storage

1.2 coordinate

There are two formats for medical image data ,dicom and nii Format , They define different directions

2 Open the image

2.1 ITK-SNAP Software

Be careful : When using this software , No Chinese in the path  

Three views  

 

3 nibabel (python library )

3.1 Basic operation

3.1.1 Import nii

import nibabel as nib
filename = 'CTC-1835078273_seg.nii'
img = nib.load(filename)
img.shape
#(512, 512, 539)

One nibable The image is composed of three parts :

  • image data , The three dimensional / Four dimensional image
  • An affine array affine,image The position of the data in the reference space
  • image Metadata (header)

3.1.2 To get an image ndarray Type data  

data = img.get_fdata()
data.shape,type(data)
#((512, 512, 539), numpy.memmap)

 3.1.3 Create a new image

At least some image data And a image Coordinate transformation matrix (affine)

import numpy as np
data = np.random.randint((32, 32, 15, 100), dtype=np.int16)
img = nib.Nifti1Image(data, np.eye(4))
nib.save(img, 'exa.nii') 

  

here numpy.memmap Is a memory image file . It is a way to treat very large binary data files on disk as arrays in memory . It allows the Divide large files into small sections for reading and writing , Instead of reading the entire array into memory at once .

memmap It also has the same method as an ordinary array , therefore , Basically as long as it can be used for ndarray Our algorithm can also be used for memmap.
 

3.2  Coordinate system and affine

In the official documentation , Provides a human brain MRI Images .

import nibabel as nib
epi_img = nib.load('someones_epi.nii.gz')
epi_img_data = epi_img.get_fdata()
epi_img_data.shape
#(53, 61, 33)

[EPI data ] Let's look at the first dimension of an array 、 Slices on the second and third dimensions .

import matplotlib.pyplot as plt
def show_slices(slices):
""" Function to display row of image slices """
fig, axes = plt.subplots(1, len(slices))
for i, slice in enumerate(slices):
axes[i].imshow(slice.T, cmap="gray", origin="lower")
slice_0 = epi_img_data[0, :, :]
slice_1 = epi_img_data[:, 0, :]
slice_2 = epi_img_data[:, :, 0]
show_slices([slice_0, slice_1, slice_2])
plt.suptitle("Center slices for EPI image") 

 image Dimension is (53, 61, 33), Think of it as 53 Zhang 61*33 Graph , Think of it as 61 Zhang 53*33 Graph , It can also be thought of as 33 Zhang 53*61 Graph

[ Structural data ( The anatomy of the )]

anat_img = nib.load('someones_anatomy.nii.gz')
anat_img_data = anat_img.get_fdata()
print(anat_img_data.shape)
#(57, 67, 56)
show_slices([anat_img_data[0, :, :],
anat_img_data[:, 0, :],
anat_img_data[:, :, 0]])
plt.suptitle("Center slices for anatomical image")

  

Usually , We have different anatomical scanning fields , So anatomical images have different shapes 、 Size and direction .

3.2.1 Voxel coordinates

Voxels are pixels with volume .

In the code above , come from EPI Data slice_0 Is from 3D Graphic 2D section . Each pixel in the slice gray image also represents a voxel , Because of this 2D The image represents 3D A slice with a certain thickness in an image .

therefore ,3D Arrays are also voxel arrays . For any array , We can all select a specific value through the index . for example , We can get... Like this EPI The value of the intermediate element in the data array :

epi_img_data[0,0,0]
#10.755071640014648

[0,0,0] Voxel coordinates

3.2.2 Voxel coordinates and space points

Voxel coordinates hardly tell us where the data comes from in the scanner . for example , Suppose we have voxel coordinates (26, 30, 16). If there is no more information , We don't know whether this voxel is on the left or right side of the brain , Or from the left or right side of the scanner . This is because the scanner allows us to collect voxel data in almost any position and direction .

So let's say we're talking about EPI chart , Rotate the scanner a little , Get the part in the red box

  

We dissected and EPI scanning , Later, we certainly hope to be able to somes_epi.nii.gz Data in and someones_anatomy.nii.gz Related to . At present, we can not do this easily , Because the anatomical images we collected are similar to EPI Images have different views and directions . Therefore, the voxel coordinates cannot correspond to each other for the time being . 

We solve this problem by tracking the relationship between voxel coordinates and some reference spaces . To be specific , Affine array (affine) Storage The relationship between the voxel coordinates in the image data and the coordinates in the reference space

“ Reference space ” Medium “ Space ” What does that mean? ? The space is defined by an ordered set of axes . For our 3D Space world , It's a group 3 Two independent axes . We can determine the space we want to use by selecting these axes . We need to select the origin of the axis 、 Direction and units .(xyz- Axis , In millimeters )

3.2.3 affine matrix

We want to put the voxel coordinates (i,j,k) Convert to reference space coordinates (x,y,z), namely (x,y,z)=f(i,j,k)

And basic matrix multiplication , You can meet

Axis expansion   rotate

Rotate around the first axis

  

Rotate around the second axis

  

  

Rotate around the third axis

  

These basic operations are combined ( Matrix multiplication ), The transformation of coordinate axis can be realized  

The above completes the correspondence of coordinate axes , But the origin of voxels (0,0,0) The corresponding is not necessarily the reference space (0,0,0) spot , Suppose the corresponding is in the reference space (a,b,c) coordinate , that , In voxels (i,j,k) The corresponding is in the reference space (x,y,z)    

3.2.4 get image Of affine

  

reference  

NII - Just Solve the File Format Problem (archiveteam.org)

How to read NIFTI format image (. nii file) (programmer.group)

What is voxel (Voxel)? - You know (zhihu.com)


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved