簡體   English   中英

更改 nifti 圖像中的體素值並保存

[英]change voxel values in nifti image and save it

我將讀取一個 nifti 圖像並更改體素的值並保存與主圖像類似但只有不同體素值的新 nifti 圖像。 換句話說,我希望分割圖像中的標簽從 0 到 7,而不是具有不同的數字。 o 編寫了下面的代碼,但我收到此錯誤:

NotImplementedError: Wrong number or type of arguments for overloaded function 'WriteImage'.

可能的 C/C++ 原型有: itk::simple::WriteImage(itk::simple::Image const &,std::string const &,bool) itk::simple::WriteImage(itk::simple::Image const &,std::vector<std::string,std::allocator<std::string >> const &,bool)

編碼:

對於 os.listdir(path) 中的 image_path:

label_name = os.path.join(path, image_path)

img = nib.load(label_name)
data = img.get_fdata()
n=0;
u=0;
m=0;
b=0;
e=0;
r=0;
s=0;
img1=img
data1 = img1.get_fdata()
for i in range (0,img.shape[0]):
    for j in range (0,img.shape[1]):
        for k in range (0,img.shape[2]):

            if data[i,j,k]==500:
                n=n+1;
                data1[i,j,k]=1;
            elif data[i,j,k]==600:
                u=u+1;
                data1[i,j,k]=2;
            elif data[i,j,k]==420:
                b=b+1;
                data1[i,j,k]=3;
            elif data[i,j,k]==550:
                e=e+1;
                data1[i,j,k]=4;
            elif data[i,j,k]==205:
                r=r+1;
                data1[i,j,k]=5;
            elif data[i,j,k]==820:
                m=m+1;
                data1[i,j,k]=6;
            elif data[i,j,k]==850:
                s=s+1;
                data1[i,j,k]=7



OUTPUT_DIR='/Volumes/CSE_BME_AXM788/home/gxa131/labelsTr_new/'  
dir1=os.path.join(OUTPUT_DIR, image_path)
sitk.WriteImage(data1,dir1)

SimpleITK 的 WriteImage function 期望 SimpleITK 圖像作為第一個參數。 NiBabel Image 的 get_fdata 方法返回一個 Numpy 數組。 如果要使用 SimpleITK 寫入圖像,則需要使用 GetImageFromArray function 將 Numpy 轉換為 SimpleITK。

請注意,您將丟失原始圖像附帶的任何元數據信息,例如像素間距。

更新:

要回答有關保留元數據的問題:

我自己沒有使用過 NiBabel,但是下面的頁面描述了如何從數據數組創建新圖像,從原始圖像中復制 header 信息: https://bic-berkeley.ZBF2151810B5140517354437B514051745443AZ。 2016 年秋季/saving_images.html

我自己會在整個過程中使用 SimpleITK。 如果您使用 SimpleITK 加載圖像並在 SimpleITK 圖像 object 上進行所有處理,則會保留所有元數據。

對於您的特定代碼,您可以使用 RelabelLabelMapFilter class 到 map 您的原始標簽(500、600、520、550、205、820、850)到(1-7),假設只有標簽。 這樣您就不必自己遍歷所有體素。 https://simpleitk.org/doxygen/latest/html/classitk_1_1simple_1_1RelabelLabelMapFilter.html#details

要計算每個 label 的體素數量,可以使用 LabelShapeStatisticsImageFilter。 同樣,這避免了手動循環遍歷體素: https://simpleitk.org/doxygen/latest/html/classitk_1_1simple_1_1LabelShapeStatisticsImageFilter.html

為了保存元數據,使用 nibabel.save 如下例所示:

new_nifti = nib.Nifti1Image(***numpy_arrray***.astype(np.float), nii_original_scan.affine)
nib.save(new_nifti, f'***path to new scan***.nii.gz')

說明:您應該將新的 NIfTI 掃描(NumPy 數組)保存為 nii 圖像。 為此,請使用Nifti1Image創建 nii object,然后使用 nibabel.save 將其保存到文件中。

Numpy_array 參數 - 是您的 numpy 數組(確保是浮點類型)。 第二個參數是加載后的原始 NIfTI 掃描(使用仿射函數)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM