1

I am new to deep learning, currently working on an image segmentation network. I managed to train the network, but the problem is to translate the network response into nii format. I cut the training sample from the CT images into 512X512 slices, and then slices into 128X128 patches. Accordingly, I transfer the patches to the input of the network and get the mask 128x128 at the output. I managed to group the masks into a numpy array. But when transferring from an array to nii and trying to impose the resulting mask on the original CT, my scales do not match. Please, tell me what could be the problem? I really appreciate any help.

For example and simplicity, I took a mask from the training sample.


input_path = PatchPathOutput
ls = os.listdir(input_path)#dir with patches(128) of inital mask
slices = []

for i in range(0, len(ls), 16):
    line1 = np.array(Image.open(input_path + '/'+ ls[i]))
    #here I get the first slice line from patches
    for j in range(1, 4):
        a = np.array(Image.open(input_path + '/'+ ls[i+j]))
        line1 = np.concatenate((line1, a), axis = 1)
    
    line2 = np.array(Image.open(input_path + '/'+ ls[i + 4]))
    for j in range(5, 8):
        a = np.array(Image.open(input_path + '/'+ ls[i+j]))
        line2 = np.concatenate((line2, a), axis = 1)

    line3 = np.array(Image.open(input_path + '/'+ ls[i + 8]))
    for j in range(9, 12):
        a = np.array(Image.open(input_path + '/'+ ls[i+j]))
        line3 = np.concatenate((line3, a), axis = 1)
        
    line4 = np.array(Image.open(input_path + '/'+ ls[i + 12]))
    for j in range(13, 16):
        a = np.array(Image.open(input_path + '/'+ ls[i+j]))
        line4 = np.concatenate((line4, a), axis = 1)
    
    #all lines to slice (512 x 512)
    slice_ = np.concatenate((line1, line2), axis = 0)
    slice_ = np.concatenate((slice_, line3), axis = 0)
    slice_ = np.concatenate((slice_, line4), axis = 0)
    
    slices.append(slice_)

    slices_ = np.asarray(slices)#shape (137, 512, 512)
    slices_ = np.swapaxes(slices_,0,2)#shape (512, 512, 137)

    import nibabel as nib

    new_image = nib.Nifti1Image(slices_, affine=np.eye(4))
    nib.save(new_image, 'new_image.nii')


Yossarian
  • 21
  • 4

1 Answers1

1

Well, I realized what the problem was, during saving, you need to use the affine transformation of the original nii image.

ct_scan = nib.load(CtPathInput + '/019.nii')

import nibabel as nib

new_image = nib.Nifti1Image(slices_, ct_scan.affine)
nib.save(new_image, 'new_image.nii')
Yossarian
  • 21
  • 4