nii文件的裁剪

对于感兴趣区域很小的情况下,需要裁剪图片

def get_and_crop_nii(file_path):

    img = load(file_path)
    img1 = torch.tensor(img.get_fdata())
    print("img = ", type(img), " img1 = ", img1.shape)

    voxel_size = img.header['pixdim'][1:] * [0] + img.header['pixdim'][:-1][::-1]
    print("Voxel size (mm):", voxel_size)

    start_x = 75  # x轴起始索引
    end_x = 350  # x轴结束索引

    start_y = 149  # y轴起始索引
    end_y = 244  # y轴结束索引

    start_z = 84  # z轴起始索引
    end_z = 160  # z轴结束索引

    new_data = img.get_fdata()[start_x: end_x + 1, start_y: end_y + 1, start_z: end_z + 1]

    print("Cropped image shape:", new_data.shape)
    """350-75 = 275 
       244-149 = 95
       160-84 = 76"""
    # Cropped image shape: (235, 96, 77)

    cropped_img = nib.Nifti1Image(new_data, img.affine)

    # nib.save(img, 'filename.nii')
    nib.save(cropped_img, "nii_crop/crop_2.nii")

    return cropped_img

裁剪前:
nii文件的裁剪_第1张图片

裁剪后:
nii文件的裁剪_第2张图片

你可能感兴趣的:(python,开发语言)