用pytorch處理醫學影象(以nifity影象為例)----持續更新中
阿新 • • 發佈:2019-01-11
在這之前,要安裝一些常用的包:
pip install nibabel----安裝用於讀寫影像資料檔案的程式包
pip install --trusted-host pypi.python.org SimpleITK-----安裝ITK包
- 影象讀取
法1:
import SimpleITK as sitk #匯入itk import numpy as np import torch .... imagenames = [os.path.join(datapath, 'patient%02d_C0.nii.gz' % i) for i in indcs] #影象路徑 .... itkimage = sitk.ReadImage(imagenames[subjectid]) #讀取資料 numpyimage = sitk.GetArrayFromImage(itkimage) #轉為numpy tensorimage = torch.from_numpy(numpyimage ).type(torch.FloatTensor) #轉為tensor ....
法2:
import numpy as np
import nibabel as nib
nibimage = nib.load(imagenames[subjectid])
imagedata = nibimage.get_data()
header = nibimage.get_header() #讀取影象資訊,後面save result in NIFITY format要用到
ref_affine = nibimage.get_affine()
numpyimage = np.array(imagedata)
- 影象常用基本操作
tensor_label = tensor.squeeze(tensor_label) #對tensor_label所有維度為1的維度壓縮 tensor_label = tensor_label.squeeze(0) #可以在指定維度對numpy進行壓縮 torch.cat((torchimage1, torchimage2), dim=0) #可以在指定維度上對tensor進行拼接 out = np.squeeze(out.numpy(), axis=0) #可以在指定維度上對numpy進行壓縮 numpylabel = np.concatenate((numpylabel, pre), axis=2) #可以在指定維度上對numpy進行拼接
- 影象儲存
predictlabel = nib.Nifti1Image(predictnumpylabel, ref_affine, header)
savefold = os.path.join(Result_DIR_PATH, 'patient%02d_C0_predict.nii.gz' % (subjectid + 31)) #儲存路徑
nib.save(predictlabel, savefold)
- 如何輸出多個label?
#--------------training data的label處理-------------- numpy2Dlabel = (numpy2Dlabel == 200) * 1 + (numpy2Dlabel == 500) * 2 + (numpy2Dlabel == 600) * 3 #輸入label處理 #--------------loss function的定義-------------- loss_func = nn.CrossEntropyLoss() # the target label is NOT an one-hotted #--------------網路結構的最後輸出-------------- outmax, a = torch.max(c10, dim=1, keepdim=True) #c10是網路的最後輸出一層 outmax = outmax.repeat(1, 4, 1, 1) #一共輸出4個label c10 = c10 - outmax out = torch.exp(c10) outsum = torch.sum(out, dim=1, keepdim=True) outsum = outsum.repeat(1, 4, 1, 1) out = torch.div(out, outsum) return out #--------------test的時候對output處理-------------- out = test_net(image) loss_output = loss(out, label) #計算predict error loss_sum += loss_output.item() out = out.data.cpu() out = np.squeeze(out.numpy(), axis=0) pre = np.argmax(out, axis=0) #最終predict的結果
- 如何自定義loss?
參考知乎上一個回答,做如下筆記: