学习记录(四):医学图像配准使用到的代码。

1.python以三视图形式显示三维.nii格式医学图像

import  nibabel as nib
from nibabel.viewers import OrthoSlicer3D

file = nib.load("path") #将.nii格式图像读入
OrthoSlicer3D(file.dataobj).show()

2.对图像进行裁剪(.nii格式)

import numpy as np
import  nibabel as nib

file = nib.load("path") #将.nii格式图像读入
vol = file.get_data() #获取图像数据
vol = vol[ : ,  ; , : ] #冒号两边写裁剪的范围,几维就有几个冒号
affine =  file.affine # afiine与变换之前保持同步
newvol = nib.NiftilImage(vol,affine) 
nibsave(newvol,'path')#保存变换后的新图像

3.ANTs对图像进行配准
安装antspy

pip install https://github.com/ANTsX/ANTsPy/release/download/v0.1.4/antspy-0.1.4-cp36-cp36m-linux_X86_64.whl

使用ANTs中的syn配准(如果.nii是float64会报错,float32不会,未知原因。)

import ants

fixed = ants.image_read("path")
moving =  ants.image_read("path")
SyN = ants.registration(fixed = fixed, moving = moving, typr_of_transform = 'SyN')
result = ants.apply_transforms(fixed = fixed, moving = moving, transformlist =            
         SyN['fwdtransforms'])
ants.image_write(result ,'path')

4.计算两图Dice

import  numpy as np
import nibabel as nib

def DSC(pred,target)
    smooth = 1e-5
    m1 = pred.flatten()
    m2 = target.flatten()
    intersection = (m1*m2).sum()
    return (2.*intersection+smooth)/(m1.sum()+m2.sum() + smooth)

def compute_label_dice(gt,pred)
    cls_lst = [1,...,35]
    dice_list = []
    for cls in cls_lst
        dice = DSC(gt == cls , pred == cls)
        dice_lst.append(dice)
    return np.mean(dice_lst)

file1 = nib.load("path") 
file2 = nib.load("path") 
vol1 = file1.get_data()
vol2 = file2.get_data()
dice = compute_label_dice(vol1.vol2)

上一篇:深拷贝的简便方法


下一篇:js的函数事件回顾