def validation(self):
        ext = '.nii.gz'
        validation_dir = 'validation'
        sct.run('mkdir ' + validation_dir)

        # loading the images
        im_ref_gm_seg = Image('../' + self.ref_gm_seg_fname)
        im_ref_wm_seg = inverse_gmseg_to_wmseg(
            im_ref_gm_seg,
            Image('../' + self.sc_seg_fname),
            im_ref_gm_seg.path + im_ref_gm_seg.file_name,
            save=False)

        res_gm_seg_bin = self.gm_seg.res_gm_seg.copy()
        res_wm_seg_bin = self.gm_seg.res_wm_seg.copy()

        if self.param.res_type == 'prob':
            res_gm_seg_bin.data = np.asarray(
                (res_gm_seg_bin.data >= 0.5).astype(int))
            res_wm_seg_bin.data = np.asarray(
                (res_wm_seg_bin.data >= 0.50001).astype(int))

        mask = Image(self.preprocessed.square_mask)

        # doing the validation
        os.chdir(validation_dir)

        im_ref_gm_seg.path = './'
        im_ref_gm_seg.file_name = 'ref_gm_seg'
        im_ref_gm_seg.ext = ext
        im_ref_gm_seg.save()
        ref_gm_seg_new_name = resample_image(im_ref_gm_seg.file_name + ext,
                                             npx=self.preprocessed.resample_to,
                                             npy=self.preprocessed.resample_to,
                                             binary=True)
        im_ref_gm_seg = Image(ref_gm_seg_new_name)
        sct.run('rm ' + ref_gm_seg_new_name)

        im_ref_wm_seg.path = './'
        im_ref_wm_seg.file_name = 'ref_wm_seg'
        im_ref_wm_seg.ext = ext
        im_ref_wm_seg.save()
        ref_wm_seg_new_name = resample_image(im_ref_wm_seg.file_name + ext,
                                             npx=self.preprocessed.resample_to,
                                             npy=self.preprocessed.resample_to,
                                             binary=True)
        im_ref_wm_seg = Image(ref_wm_seg_new_name)
        sct.run('rm ' + ref_wm_seg_new_name)

        ref_orientation = im_ref_gm_seg.orientation
        im_ref_gm_seg.change_orientation('IRP')
        im_ref_wm_seg.change_orientation('IRP')

        im_ref_gm_seg.crop_and_stack(mask, save=False)
        im_ref_wm_seg.crop_and_stack(mask, save=False)

        im_ref_gm_seg.change_orientation('RPI')
        im_ref_wm_seg.change_orientation('RPI')

        # saving the images to call the validation functions
        res_gm_seg_bin.path = './'
        res_gm_seg_bin.file_name = 'res_gm_seg_bin'
        res_gm_seg_bin.ext = ext
        res_gm_seg_bin.save()

        res_wm_seg_bin.path = './'
        res_wm_seg_bin.file_name = 'res_wm_seg_bin'
        res_wm_seg_bin.ext = ext
        res_wm_seg_bin.save()

        im_ref_gm_seg.path = './'
        im_ref_gm_seg.file_name = 'ref_gm_seg'
        im_ref_gm_seg.ext = ext
        im_ref_gm_seg.save()

        im_ref_wm_seg.path = './'
        im_ref_wm_seg.file_name = 'ref_wm_seg'
        im_ref_wm_seg.ext = ext
        im_ref_wm_seg.save()

        sct.run('sct_orientation -i ' + res_gm_seg_bin.file_name + ext +
                ' -s RPI')
        res_gm_seg_bin.file_name += '_RPI'
        sct.run('sct_orientation -i ' + res_wm_seg_bin.file_name + ext +
                ' -s RPI')
        res_wm_seg_bin.file_name += '_RPI'

        res_gm_seg_bin = Image(res_gm_seg_bin.file_name + ext)
        im_ref_gm_seg.hdr.set_zooms(
            res_gm_seg_bin.hdr.get_zooms())  # correcting the pix dimension
        im_ref_gm_seg.save()

        res_wm_seg_bin = Image(res_wm_seg_bin.file_name + ext)
        im_ref_wm_seg.hdr.set_zooms(
            res_wm_seg_bin.hdr.get_zooms())  # correcting the pix dimension
        im_ref_wm_seg.save()

        # Dice
        try:
            status_gm, output_gm = sct.run(
                'sct_dice_coefficient ' + im_ref_gm_seg.file_name + ext + ' ' +
                res_gm_seg_bin.file_name + ext + '  -2d-slices 2',
                error_exit='warning',
                raise_exception=True)
        except Exception:
            sct.run('c3d ' + res_gm_seg_bin.file_name + ext + ' ' +
                    im_ref_gm_seg.file_name + ext + ' -reslice-identity -o ' +
                    im_ref_gm_seg.file_name + '_in_res_space' + ext)
            sct.run('fslmaths ' + im_ref_gm_seg.file_name + '_in_res_space' +
                    ext + ' -thr 0.1 ' + im_ref_gm_seg.file_name +
                    '_in_res_space' + ext)
            sct.run('fslmaths ' + im_ref_gm_seg.file_name + '_in_res_space' +
                    ext + ' -bin ' + im_ref_gm_seg.file_name +
                    '_in_res_space' + ext)
            status_gm, output_gm = sct.run(
                'sct_dice_coefficient ' + im_ref_gm_seg.file_name +
                '_in_res_space' + ext + ' ' + res_gm_seg_bin.file_name + ext +
                '  -2d-slices 2',
                error_exit='warning')
        try:
            status_wm, output_wm = sct.run(
                'sct_dice_coefficient ' + im_ref_wm_seg.file_name + ext + ' ' +
                res_wm_seg_bin.file_name + ext + '  -2d-slices 2',
                error_exit='warning',
                raise_exception=True)
        except Exception:
            sct.run('c3d ' + res_wm_seg_bin.file_name + ext + ' ' +
                    im_ref_wm_seg.file_name + ext + ' -reslice-identity -o ' +
                    im_ref_wm_seg.file_name + '_in_res_space' + ext)
            sct.run('fslmaths ' + im_ref_wm_seg.file_name + '_in_res_space' +
                    ext + ' -thr 0.1 ' + im_ref_wm_seg.file_name +
                    '_in_res_space' + ext)
            sct.run('fslmaths ' + im_ref_wm_seg.file_name + '_in_res_space' +
                    ext + ' -bin ' + im_ref_wm_seg.file_name +
                    '_in_res_space' + ext)
            status_wm, output_wm = sct.run(
                'sct_dice_coefficient ' + im_ref_wm_seg.file_name +
                '_in_res_space' + ext + ' ' + res_wm_seg_bin.file_name + ext +
                '  -2d-slices 2',
                error_exit='warning')

        dice_name = 'dice_' + sct.extract_fname(
            self.target_fname)[1] + '_' + self.param.res_type + '.txt'
        dice_fic = open('../../' + dice_name, 'w')
        if self.param.res_type == 'prob':
            dice_fic.write(
                'WARNING : the probabilistic segmentations were binarized with a threshold at 0.5 to compute the dice coefficient \n'
            )
        dice_fic.write(
            '\n--------------------------------------------------------------\n'
            'Dice coefficient on the Gray Matter segmentation:\n')
        dice_fic.write(output_gm)
        dice_fic.write(
            '\n\n--------------------------------------------------------------\n'
            'Dice coefficient on the White Matter segmentation:\n')
        dice_fic.write(output_wm)
        dice_fic.close()
        # sct.run(' mv ./' + dice_name + ' ../')

        hd_name = 'hd_' + sct.extract_fname(
            self.target_fname)[1] + '_' + self.param.res_type + '.txt'
        sct.run('sct_compute_hausdorff_distance.py -i ' +
                res_gm_seg_bin.file_name + ext + ' -r ' +
                im_ref_gm_seg.file_name + ext + ' -t 1 -o ' + hd_name +
                ' -v ' + str(self.param.verbose))
        sct.run('mv ./' + hd_name + ' ../../')

        os.chdir('..')
        return dice_name, hd_name
    def validation(self):
        ext = '.nii.gz'
        validation_dir = 'validation'
        sct.run('mkdir ' + validation_dir)

        # loading the images
        im_ref_gm_seg = Image('../' + self.ref_gm_seg_fname)
        im_ref_wm_seg = inverse_gmseg_to_wmseg(im_ref_gm_seg, Image('../' + self.sc_seg_fname), im_ref_gm_seg.path + im_ref_gm_seg.file_name, save=False)

        res_gm_seg_bin = self.gm_seg.res_gm_seg.copy()
        res_wm_seg_bin = self.gm_seg.res_wm_seg.copy()

        if self.param.res_type == 'prob':
            res_gm_seg_bin.data = np.asarray((res_gm_seg_bin.data >= 0.5).astype(int))
            res_wm_seg_bin.data = np.asarray((res_wm_seg_bin.data >= 0.50001).astype(int))

        mask = Image(self.preprocessed.square_mask)

        # doing the validation
        os.chdir(validation_dir)

        im_ref_gm_seg.path = './'
        im_ref_gm_seg.file_name = 'ref_gm_seg'
        im_ref_gm_seg.ext = ext
        im_ref_gm_seg.save()
        ref_gm_seg_new_name = resample_image(im_ref_gm_seg.file_name + ext, npx=self.preprocessed.resample_to, npy=self.preprocessed.resample_to, binary=True)
        im_ref_gm_seg = Image(ref_gm_seg_new_name)
        sct.run('rm ' + ref_gm_seg_new_name)

        im_ref_wm_seg.path = './'
        im_ref_wm_seg.file_name = 'ref_wm_seg'
        im_ref_wm_seg.ext = ext
        im_ref_wm_seg.save()
        ref_wm_seg_new_name = resample_image(im_ref_wm_seg.file_name + ext, npx=self.preprocessed.resample_to, npy=self.preprocessed.resample_to, binary=True)
        im_ref_wm_seg = Image(ref_wm_seg_new_name)
        sct.run('rm ' + ref_wm_seg_new_name)

        ref_orientation = im_ref_gm_seg.orientation
        im_ref_gm_seg.change_orientation('IRP')
        im_ref_wm_seg.change_orientation('IRP')

        im_ref_gm_seg.crop_and_stack(mask, save=False)
        im_ref_wm_seg.crop_and_stack(mask, save=False)

        im_ref_gm_seg.change_orientation('RPI')
        im_ref_wm_seg.change_orientation('RPI')

        # saving the images to call the validation functions
        res_gm_seg_bin.path = './'
        res_gm_seg_bin.file_name = 'res_gm_seg_bin'
        res_gm_seg_bin.ext = ext
        res_gm_seg_bin.save()

        res_wm_seg_bin.path = './'
        res_wm_seg_bin.file_name = 'res_wm_seg_bin'
        res_wm_seg_bin.ext = ext
        res_wm_seg_bin.save()

        im_ref_gm_seg.path = './'
        im_ref_gm_seg.file_name = 'ref_gm_seg'
        im_ref_gm_seg.ext = ext
        im_ref_gm_seg.save()

        im_ref_wm_seg.path = './'
        im_ref_wm_seg.file_name = 'ref_wm_seg'
        im_ref_wm_seg.ext = ext
        im_ref_wm_seg.save()

        sct.run('sct_orientation -i ' + res_gm_seg_bin.file_name + ext + ' -s RPI')
        res_gm_seg_bin.file_name += '_RPI'
        sct.run('sct_orientation -i ' + res_wm_seg_bin.file_name + ext + ' -s RPI')
        res_wm_seg_bin.file_name += '_RPI'

        res_gm_seg_bin = Image(res_gm_seg_bin.file_name + ext)
        im_ref_gm_seg.hdr.set_zooms(res_gm_seg_bin.hdr.get_zooms())  # correcting the pix dimension
        im_ref_gm_seg.save()

        res_wm_seg_bin = Image(res_wm_seg_bin.file_name + ext)
        im_ref_wm_seg.hdr.set_zooms(res_wm_seg_bin.hdr.get_zooms())  # correcting the pix dimension
        im_ref_wm_seg.save()

        # Dice
        try:
            status_gm, output_gm = sct.run('sct_dice_coefficient ' + im_ref_gm_seg.file_name + ext + ' ' + res_gm_seg_bin.file_name + ext + '  -2d-slices 2', error_exit='warning', raise_exception=True)
        except Exception:
            sct.run('c3d ' + res_gm_seg_bin.file_name + ext + ' ' + im_ref_gm_seg.file_name + ext + ' -reslice-identity -o ' + im_ref_gm_seg.file_name + '_in_res_space' + ext)
            sct.run('fslmaths ' + im_ref_gm_seg.file_name + '_in_res_space' + ext + ' -thr 0.1 ' + im_ref_gm_seg.file_name + '_in_res_space' + ext )
            sct.run('fslmaths ' + im_ref_gm_seg.file_name + '_in_res_space' + ext + ' -bin ' + im_ref_gm_seg.file_name + '_in_res_space' + ext )
            status_gm, output_gm = sct.run('sct_dice_coefficient ' + im_ref_gm_seg.file_name + '_in_res_space' + ext + ' ' + res_gm_seg_bin.file_name + ext + '  -2d-slices 2', error_exit='warning')
        try:
            status_wm, output_wm = sct.run('sct_dice_coefficient ' + im_ref_wm_seg.file_name + ext + ' ' + res_wm_seg_bin.file_name + ext + '  -2d-slices 2', error_exit='warning', raise_exception=True)
        except Exception:
            sct.run('c3d ' + res_wm_seg_bin.file_name + ext + ' ' + im_ref_wm_seg.file_name + ext + ' -reslice-identity -o ' + im_ref_wm_seg.file_name + '_in_res_space' + ext)
            sct.run('fslmaths ' + im_ref_wm_seg.file_name + '_in_res_space' + ext + ' -thr 0.1 ' + im_ref_wm_seg.file_name + '_in_res_space' + ext)
            sct.run('fslmaths ' + im_ref_wm_seg.file_name + '_in_res_space' + ext + ' -bin ' + im_ref_wm_seg.file_name + '_in_res_space' + ext)
            status_wm, output_wm = sct.run('sct_dice_coefficient ' + im_ref_wm_seg.file_name + '_in_res_space' + ext + ' ' + res_wm_seg_bin.file_name + ext + '  -2d-slices 2', error_exit='warning')

        dice_name = 'dice_' + sct.extract_fname(self.target_fname)[1] + '_' + self.param.res_type + '.txt'
        dice_fic = open('../../' + dice_name, 'w')
        if self.param.res_type == 'prob':
            dice_fic.write('WARNING : the probabilistic segmentations were binarized with a threshold at 0.5 to compute the dice coefficient \n')
        dice_fic.write('\n--------------------------------------------------------------\n'
                       'Dice coefficient on the Gray Matter segmentation:\n')
        dice_fic.write(output_gm)
        dice_fic.write('\n\n--------------------------------------------------------------\n'
                       'Dice coefficient on the White Matter segmentation:\n')
        dice_fic.write(output_wm)
        dice_fic.close()
        # sct.run(' mv ./' + dice_name + ' ../')

        hd_name = 'hd_' + sct.extract_fname(self.target_fname)[1] + '_' + self.param.res_type + '.txt'
        sct.run('sct_compute_hausdorff_distance.py -i ' + res_gm_seg_bin.file_name + ext + ' -r ' + im_ref_gm_seg.file_name + ext + ' -t 1 -o ' + hd_name + ' -v ' + str(self.param.verbose))
        sct.run('mv ./' + hd_name + ' ../../')

        os.chdir('..')
        return dice_name, hd_name
def crop_image_around_segmentation(
    fname_in, fname_seg, path_output_im, path_output_seg, size_crop, offset, remove_tmp_files, verbose
):
    # 1. Resample to 1mm^3 isotropic
    fname_in_resampled = sct.add_suffix(fname_in, "r")
    sct.run("sct_resample -i " + fname_in + " -mm 1x1x1 -o " + fname_in_resampled, verbose=verbose)
    fname_in = fname_in_resampled
    fname_seg_resample = sct.add_suffix(fname_seg, "r")
    sct.run("sct_resample -i " + fname_seg + " -mm 1x1x1 -o " + fname_seg_resample, verbose=verbose)
    fname_seg = fname_seg_resample

    # 2. Orient both input images to RPI for the sake of simplicity
    sct.run("sct_image -i " + fname_in + " -setorient RPI", verbose=verbose)
    fname_in = sct.add_suffix(fname_in, "_RPI")
    sct.run("sct_image -i " + fname_seg + " -setorient RPI", verbose=verbose)
    fname_seg = sct.add_suffix(fname_seg, "_RPI")

    # 3. Pad both images to avoid edge issues when cropping
    fname_in_pad = sct.add_suffix(fname_in, "p")
    pad_image = str(int(int(size_crop) / 2))
    sct.run(
        "sct_image -i " + fname_in + " -pad " + pad_image + "," + pad_image + ",0 -o " + fname_in_pad, verbose=verbose
    )
    fname_in = fname_in_pad
    fname_seg_pad = sct.add_suffix(fname_seg, "p")
    sct.run(
        "sct_image -i " + fname_seg + " -pad " + pad_image + "," + pad_image + ",0 -o " + fname_seg_pad, verbose=verbose
    )
    fname_seg = fname_seg_pad

    # 4. Extract centerline from segmentation
    fname_centerline = sct.add_suffix(fname_seg, "_centerline")
    sct.run("sct_process_segmentation -i " + fname_seg + " -p centerline", verbose=verbose)  # -o ' + fname_centerline)

    # 5. Create a square mask around the spinal cord centerline
    fname_mask_box = "mask_box.nii.gz"
    sct.run(
        "sct_create_mask -i "
        + fname_in
        + " -m centerline,"
        + fname_centerline
        + " -s "
        + str(size_crop)
        + " -o "
        + fname_mask_box
        + " -f box -e 1 -k "
        + offset,
        verbose=verbose,
    )

    # 6. Crop image around the spinal cord and create a stack of square images
    sct.printv("Cropping around mask and stacking slices...", verbose=verbose)
    im_mask_box = Image(fname_mask_box)
    im_input = Image(fname_in)
    im_input.crop_and_stack(im_mask_box, suffix="_stack", save=True)
    im_seg = Image(fname_seg)
    im_seg.crop_and_stack(im_mask_box, suffix="_stack", save=True)

    # 6.5 Change name of images
    fname_stack_image = sct.add_suffix(fname_in, "_stack")
    fname_stack_seg = sct.add_suffix(fname_seg, "_stack")
    import random

    output_im_filename = str(random.randint(1, 1000000000000))
    output_im_fname = output_im_filename + "_im.nii.gz"
    output_seg_fname = output_im_filename + "_seg.nii.gz"
    sct.run("mv " + fname_stack_image + " " + output_im_fname, verbose=verbose)
    sct.run("mv " + fname_stack_seg + " " + output_seg_fname, verbose=verbose)

    # 7. Split the two stack images and save each slice
    sct.run("sct_image -i " + output_im_fname + " -split z", verbose=verbose)
    sct.run("sct_image -i " + output_seg_fname + " -split z", verbose=verbose)

    # 8. Move all images to output folders
    path_fname, file_fname, ext_fname = sct.extract_fname(output_im_fname)
    sct.run("mv " + file_fname + "_* " + path_output_im, verbose=verbose)
    path_fname, file_fname, ext_fname = sct.extract_fname(output_seg_fname)
    sct.run("mv " + file_fname + "_* " + path_output_seg, verbose=verbose)
def crop_image_around_segmentation(fname_in, fname_seg, path_output_im,
                                   path_output_seg, size_crop, offset,
                                   remove_tmp_files, verbose):
    # 1. Resample to 1mm^3 isotropic
    fname_in_resampled = sct.add_suffix(fname_in, 'r')
    sct.run('sct_resample -i ' + fname_in + ' -mm 1x1x1 -o ' +
            fname_in_resampled,
            verbose=verbose)
    fname_in = fname_in_resampled
    fname_seg_resample = sct.add_suffix(fname_seg, 'r')
    sct.run('sct_resample -i ' + fname_seg + ' -mm 1x1x1 -o ' +
            fname_seg_resample,
            verbose=verbose)
    fname_seg = fname_seg_resample

    # 2. Orient both input images to RPI for the sake of simplicity
    sct.run('sct_image -i ' + fname_in + ' -setorient RPI', verbose=verbose)
    fname_in = sct.add_suffix(fname_in, '_RPI')
    sct.run('sct_image -i ' + fname_seg + ' -setorient RPI', verbose=verbose)
    fname_seg = sct.add_suffix(fname_seg, '_RPI')

    # 3. Pad both images to avoid edge issues when cropping
    fname_in_pad = sct.add_suffix(fname_in, 'p')
    pad_image = str(int(int(size_crop) / 2))
    sct.run('sct_image -i ' + fname_in + ' -pad ' + pad_image + ',' +
            pad_image + ',0 -o ' + fname_in_pad,
            verbose=verbose)
    fname_in = fname_in_pad
    fname_seg_pad = sct.add_suffix(fname_seg, 'p')
    sct.run('sct_image -i ' + fname_seg + ' -pad ' + pad_image + ',' +
            pad_image + ',0 -o ' + fname_seg_pad,
            verbose=verbose)
    fname_seg = fname_seg_pad

    # 4. Extract centerline from segmentation
    fname_centerline = sct.add_suffix(fname_seg, '_centerline')
    sct.run('sct_process_segmentation -i ' + fname_seg + ' -p centerline',
            verbose=verbose)  # -o ' + fname_centerline)

    # 5. Create a square mask around the spinal cord centerline
    fname_mask_box = 'mask_box.nii.gz'
    sct.run('sct_create_mask -i ' + fname_in + ' -m centerline,' +
            fname_centerline + ' -s ' + str(size_crop) + ' -o ' +
            fname_mask_box + ' -f box -e 1 -k ' + offset,
            verbose=verbose)

    # 6. Crop image around the spinal cord and create a stack of square images
    sct.printv('Cropping around mask and stacking slices...', verbose=verbose)
    im_mask_box = Image(fname_mask_box)
    im_input = Image(fname_in)
    im_input.crop_and_stack(im_mask_box, suffix='_stack', save=True)
    im_seg = Image(fname_seg)
    im_seg.crop_and_stack(im_mask_box, suffix='_stack', save=True)

    # 6.5 Change name of images
    fname_stack_image = sct.add_suffix(fname_in, '_stack')
    fname_stack_seg = sct.add_suffix(fname_seg, '_stack')
    import random
    output_im_filename = str(random.randint(1, 1000000000000))
    output_im_fname = output_im_filename + '_im.nii.gz'
    output_seg_fname = output_im_filename + '_seg.nii.gz'
    sct.run('mv ' + fname_stack_image + ' ' + output_im_fname, verbose=verbose)
    sct.run('mv ' + fname_stack_seg + ' ' + output_seg_fname, verbose=verbose)

    # 7. Split the two stack images and save each slice
    sct.run('sct_image -i ' + output_im_fname + ' -split z', verbose=verbose)
    sct.run('sct_image -i ' + output_seg_fname + ' -split z', verbose=verbose)

    # 8. Move all images to output folders
    path_fname, file_fname, ext_fname = sct.extract_fname(output_im_fname)
    sct.run('mv ' + file_fname + '_* ' + path_output_im, verbose=verbose)
    path_fname, file_fname, ext_fname = sct.extract_fname(output_seg_fname)
    sct.run('mv ' + file_fname + '_* ' + path_output_seg, verbose=verbose)