def run_main():
    sct.init_sct()
    parser = get_parser()
    args = sys.argv[1:]
    arguments = parser.parse(args)

    # Input filename
    fname_input_data = arguments["-i"]
    fname_data = os.path.abspath(fname_input_data)

    # Method used
    method = 'optic'
    if "-method" in arguments:
        method = arguments["-method"]

    # Contrast type
    contrast_type = ''
    if "-c" in arguments:
        contrast_type = arguments["-c"]
    if method == 'optic' and not contrast_type:
        # Contrast must be
        error = 'ERROR: -c is a mandatory argument when using Optic method.'
        sct.printv(error, type='error')
        return

    # Ga between slices
    interslice_gap = 10.0
    if "-gap" in arguments:
        interslice_gap = float(arguments["-gap"])

    # Output folder
    if "-ofolder" in arguments:
        folder_output = arguments["-ofolder"]
    else:
        folder_output = '.'

    # Remove temporary files
    remove_temp_files = True
    if "-r" in arguments:
        remove_temp_files = bool(int(arguments["-r"]))

    # Outputs a ROI file
    output_roi = False
    if "-roi" in arguments:
        output_roi = bool(int(arguments["-roi"]))

    # Verbosity
    verbose = 0
    if "-v" in arguments:
        verbose = int(arguments["-v"])

    if method == 'viewer':
        fname_labels_viewer = _call_viewer_centerline(
            fname_in=fname_data, interslice_gap=interslice_gap)
        centerline_filename = extract_centerline(
            fname_labels_viewer,
            remove_temp_files=remove_temp_files,
            verbose=verbose,
            algo_fitting='nurbs',
            nurbs_pts_number=8000)

    else:
        # condition on verbose when using OptiC
        if verbose == 1:
            verbose = 2

        # OptiC models
        path_script = os.path.dirname(__file__)
        path_sct = os.path.dirname(path_script)
        optic_models_path = os.path.join(path_sct, 'data', 'optic_models',
                                         '{}_model'.format(contrast_type))

        # Execute OptiC binary
        _, centerline_filename = optic.detect_centerline(
            image_fname=fname_data,
            contrast_type=contrast_type,
            optic_models_path=optic_models_path,
            folder_output=folder_output,
            remove_temp_files=remove_temp_files,
            output_roi=output_roi,
            verbose=verbose)

    sct.display_viewer_syntax([fname_input_data, centerline_filename],
                              colormaps=['gray', 'red'],
                              opacities=['', '1'])
def get_centerline_from_labels(
    fname_in, list_fname_labels, param, output_file_name=None, remove_temp_files=1, verbose=0
):

    path, file, ext = sct.extract_fname(fname_in)

    # create temporary folder
    path_tmp = sct.slash_at_the_end("tmp." + strftime("%y%m%d%H%M%S"), 1)
    sct.run("mkdir " + path_tmp)

    # Copying input data to tmp folder
    sct.printv("\nCopying input data to tmp folder...", verbose)
    sct.run("sct_convert -i " + fname_in + " -o " + path_tmp + "data.nii")
    file_labels = []
    for i in range(len(list_fname_labels)):
        file_labels.append("labels_" + str(i) + ".nii.gz")
        sct.run("sct_convert -i " + list_fname_labels[i] + " -o " + path_tmp + file_labels[i])

    # go to tmp folder
    os.chdir(path_tmp)

    ## Concatenation of the files

    # Concatenation : sum of matrices
    file_0 = Image("data.nii")
    data_concatenation = file_0.data
    hdr_0 = file_0.hdr
    orientation_file_0 = get_orientation_3d(file_0)
    if len(list_fname_labels) > 0:
        for i in range(0, len(list_fname_labels)):
            orientation_file_temp = get_orientation_3d(file_labels[i], filename=True)
            if orientation_file_0 != orientation_file_temp:
                print "ERROR: The files ", fname_in, " and ", file_labels[
                    i
                ], " are not in the same orientation. Use sct_image -setorient to change the orientation of a file."
                sys.exit(2)
            file_temp = load(file_labels[i])
            data_temp = file_temp.get_data()
            data_concatenation = data_concatenation + data_temp

    # Save concatenation as a file
    print "\nWrite NIFTI volumes..."
    img = Nifti1Image(data_concatenation, None, hdr_0)
    save(img, "concatenation_file.nii.gz")

    # Applying nurbs to the concatenation and save file as binary file
    fname_output = extract_centerline(
        "concatenation_file.nii.gz",
        remove_temp_files=remove_temp_files,
        verbose=verbose,
        algo_fitting=param.algo_fitting,
        type_window=param.type_window,
        window_length=param.window_length,
    )

    # Rename files after processing
    if output_file_name != None:
        output_file_name = output_file_name
    else:
        output_file_name = "generated_centerline.nii.gz"

    os.rename(fname_output, output_file_name)
    path_binary, file_binary, ext_binary = sct.extract_fname(output_file_name)
    os.rename("concatenation_file_centerline.txt", file_binary + ".txt")

    # Process for a binary file as output:
    sct.run("cp " + output_file_name + " ../")

    # Process for a text file as output:
    sct.run("cp " + file_binary + ".txt" + " ../")

    os.chdir("../")
    # Remove temporary files
    if remove_temp_files:
        print ("\nRemove temporary files...")
        sct.run("rm -rf " + path_tmp, error_exit="warning")
Example #3
0
def main(list_file,
         param,
         output_file_name=None,
         remove_temp_files=1,
         verbose=0):

    path, file, ext = sct.extract_fname(list_file[0])

    # create temporary folder
    path_tmp = 'tmp.' + time.strftime("%y%m%d%H%M%S")
    sct.run('mkdir ' + path_tmp)

    # copy files into tmp folder
    sct.printv('\nCopy files into tmp folder...', verbose)
    for i in range(len(list_file)):
        file_temp = os.path.abspath(list_file[i])
        sct.run('cp ' + file_temp + ' ' + path_tmp)

    # go to tmp folder
    os.chdir(path_tmp)

    ## Concatenation of the files

    # Concatenation : sum of matrices
    file_0 = load(file + ext)
    data_concatenation = file_0.get_data()
    hdr_0 = file_0.get_header()
    orientation_file_0 = get_orientation(list_file[0])
    if len(list_file) > 0:
        for i in range(1, len(list_file)):
            orientation_file_temp = get_orientation(list_file[i])
            if orientation_file_0 != orientation_file_temp:
                print "ERROR: The files ", list_file[0], " and ", list_file[
                    i], " are not in the same orientation. Use sct_orientation to change the orientation of a file."
                sys.exit(2)
            file_temp = load(list_file[i])
            data_temp = file_temp.get_data()
            data_concatenation = data_concatenation + data_temp

    # Save concatenation as a file
    print '\nWrite NIFTI volumes...'
    img = Nifti1Image(data_concatenation, None, hdr_0)
    save(img, 'concatenation_file.nii.gz')

    # Applying nurbs to the concatenation and save file as binary file
    fname_output = extract_centerline('concatenation_file.nii.gz',
                                      remove_temp_files=remove_temp_files,
                                      verbose=verbose,
                                      algo_fitting=param.algo_fitting,
                                      type_window=param.type_window,
                                      window_length=param.window_length)

    # Rename files after processing
    if output_file_name != None:
        output_file_name = output_file_name
    else:
        output_file_name = "generated_centerline.nii.gz"

    os.rename(fname_output, output_file_name)
    path_binary, file_binary, ext_binary = sct.extract_fname(output_file_name)
    os.rename('concatenation_file_centerline.txt', file_binary + '.txt')

    # Process for a binary file as output:
    sct.run('cp ' + output_file_name + ' ../')

    # Process for a text file as output:
    sct.run('cp ' + file_binary + '.txt' + ' ../')

    os.chdir('../')
    # Remove temporary files
    if remove_temp_files:
        print('\nRemove temporary files...')
        sct.run('rm -rf ' + path_tmp)
def find_centerline(algo, image_fname, path_sct, contrast_type, brain_bool,
                    folder_output, remove_temp_files, centerline_fname):

    if Image(image_fname).dim[2] == 1:  # isct_spine_detect requires nz > 1
        from sct_image import concat_data
        im_concat = concat_data([image_fname, image_fname], dim=2)
        im_concat.save(sct.add_suffix(image_fname, '_concat'))
        image_fname = sct.add_suffix(image_fname, '_concat')
        bool_2d = True
    else:
        bool_2d = False

    if algo == 'svm':
        # run optic on a heatmap computed by a trained SVM+HoG algorithm
        optic_models_fname = os.path.join(path_sct, 'data', 'optic_models',
                                          '{}_model'.format(contrast_type))
        _, centerline_filename = optic.detect_centerline(
            image_fname=image_fname,
            contrast_type=contrast_type,
            optic_models_path=optic_models_fname,
            folder_output=folder_output,
            remove_temp_files=remove_temp_files,
            output_roi=False,
            verbose=0)
    elif algo == 'cnn':
        # CNN parameters
        dct_patch_ctr = {
            't2': {
                'size': (80, 80),
                'mean': 51.1417,
                'std': 57.4408
            },
            't2s': {
                'size': (80, 80),
                'mean': 68.8591,
                'std': 71.4659
            },
            't1': {
                'size': (80, 80),
                'mean': 55.7359,
                'std': 64.3149
            },
            'dwi': {
                'size': (80, 80),
                'mean': 55.744,
                'std': 45.003
            }
        }
        dct_params_ctr = {
            't2': {
                'features': 16,
                'dilation_layers': 2
            },
            't2s': {
                'features': 8,
                'dilation_layers': 3
            },
            't1': {
                'features': 24,
                'dilation_layers': 3
            },
            'dwi': {
                'features': 8,
                'dilation_layers': 2
            }
        }

        # load model
        ctr_model_fname = os.path.join(path_sct, 'data', 'deepseg_sc_models',
                                       '{}_ctr.h5'.format(contrast_type))
        ctr_model = nn_architecture_ctr(
            height=dct_patch_ctr[contrast_type]['size'][0],
            width=dct_patch_ctr[contrast_type]['size'][1],
            channels=1,
            classes=1,
            features=dct_params_ctr[contrast_type]['features'],
            depth=2,
            temperature=1.0,
            padding='same',
            batchnorm=True,
            dropout=0.0,
            dilation_layers=dct_params_ctr[contrast_type]['dilation_layers'])
        ctr_model.load_weights(ctr_model_fname)

        # compute the heatmap
        fname_heatmap = sct.add_suffix(image_fname, "_heatmap")
        img_filename = ''.join(sct.extract_fname(fname_heatmap)[:2])
        fname_heatmap_nii = img_filename + '.nii'
        z_max = heatmap(filename_in=image_fname,
                        filename_out=fname_heatmap_nii,
                        model=ctr_model,
                        patch_shape=dct_patch_ctr[contrast_type]['size'],
                        mean_train=dct_patch_ctr[contrast_type]['mean'],
                        std_train=dct_patch_ctr[contrast_type]['std'],
                        brain_bool=brain_bool)

        # run optic on the heatmap
        centerline_filename = sct.add_suffix(fname_heatmap, "_ctr")
        heatmap2optic(fname_heatmap=fname_heatmap_nii,
                      lambda_value=7 if contrast_type == 't2s' else 1,
                      fname_out=centerline_filename,
                      z_max=z_max if brain_bool else None)

    elif algo == 'viewer':
        centerline_filename = sct.add_suffix(image_fname, "_ctr")
        fname_labels_viewer = _call_viewer_centerline(fname_in=image_fname)
        centerline_filename = extract_centerline(fname_labels_viewer,
                                                 remove_temp_files=True,
                                                 algo_fitting='nurbs',
                                                 nurbs_pts_number=8000)

    elif algo == 'manual':
        centerline_filename = sct.add_suffix(image_fname, "_ctr")
        image_manual_centerline = Image(centerline_fname)
        # Re-orient and Re-sample the manual centerline
        image_centerline_reoriented = msct_image.change_orientation(
            image_manual_centerline, 'RPI').save(centerline_filename)
        input_resolution = image_centerline_reoriented.dim[4:7]
        new_resolution = 'x'.join(['0.5', '0.5', str(input_resolution[2])])
        spinalcordtoolbox.resample.nipy_resample.resample_file(
            centerline_filename,
            centerline_filename,
            new_resolution,
            'mm',
            'linear',
            verbose=0)

    else:
        sct.log.error(
            'The parameter "-centerline" is incorrect. Please try again.')
        sys.exit(1)

    if bool_2d:
        from sct_image import split_data
        im_split_lst = split_data(Image(centerline_filename), dim=2)
        im_split_lst[0].save(centerline_filename)

    return centerline_filename
def main(list_file, param, output_file_name=None, remove_temp_files = 1, verbose = 0):

    path, file, ext = sct.extract_fname(list_file[0])

    # create temporary folder
    path_tmp = 'tmp.'+time.strftime("%y%m%d%H%M%S")
    sct.run('mkdir '+path_tmp)

    # copy files into tmp folder
    sct.printv('\nCopy files into tmp folder...', verbose)
    for i in range(len(list_file)):
       file_temp = os.path.abspath(list_file[i])
       sct.run('cp '+file_temp+' '+path_tmp)

    # go to tmp folder
    os.chdir(path_tmp)

    ## Concatenation of the files

    # Concatenation : sum of matrices
    file_0 = load(file+ext)
    data_concatenation = file_0.get_data()
    hdr_0 = file_0.get_header()
    orientation_file_0 = get_orientation(list_file[0])
    if len(list_file)>0:
       for i in range(1, len(list_file)):
           orientation_file_temp = get_orientation(list_file[i])
           if orientation_file_0 != orientation_file_temp :
               print "ERROR: The files ", list_file[0], " and ", list_file[i], " are not in the same orientation. Use sct_orientation to change the orientation of a file."
               sys.exit(2)
           file_temp = load(list_file[i])
           data_temp = file_temp.get_data()
           data_concatenation = data_concatenation + data_temp

    # Save concatenation as a file
    print '\nWrite NIFTI volumes...'
    img = Nifti1Image(data_concatenation, None, hdr_0)
    save(img,'concatenation_file.nii.gz')


    # Applying nurbs to the concatenation and save file as binary file
    fname_output = extract_centerline('concatenation_file.nii.gz', remove_temp_files = remove_temp_files, verbose = verbose, algo_fitting=param.algo_fitting, type_window=param.type_window, window_length=param.window_length)

    # Rename files after processing
    if output_file_name != None:
       output_file_name = output_file_name
    else : output_file_name = "generated_centerline.nii.gz"

    os.rename(fname_output, output_file_name)
    path_binary, file_binary, ext_binary = sct.extract_fname(output_file_name)
    os.rename('concatenation_file_centerline.txt', file_binary+'.txt')

    # Process for a binary file as output:
    sct.run('cp '+output_file_name+' ../')

    # Process for a text file as output:
    sct.run('cp '+file_binary+ '.txt'+ ' ../')

    os.chdir('../')
    # Remove temporary files
    if remove_temp_files:
       print('\nRemove temporary files...')
       sct.run('rm -rf '+path_tmp)
def get_centerline_from_labels(fname_in, list_fname_labels, param, output_file_name=None, remove_temp_files=1, verbose=0):

    path, file, ext = sct.extract_fname(fname_in)

    # create temporary folder
    path_tmp = sct.slash_at_the_end('tmp.'+strftime('%y%m%d%H%M%S'), 1)
    sct.run('mkdir '+path_tmp)

    # Copying input data to tmp folder
    sct.printv('\nCopying input data to tmp folder...', verbose)
    sct.run('sct_convert -i '+fname_in+' -o '+path_tmp+'data.nii')
    file_labels = []
    for i in range(len(list_fname_labels)):
        file_labels.append('labels_'+str(i)+'.nii.gz')
        sct.run('sct_convert -i '+list_fname_labels[i]+' -o '+path_tmp+file_labels[i])

    # go to tmp folder
    os.chdir(path_tmp)

    ## Concatenation of the files

    # Concatenation : sum of matrices
    file_0 = Image('data.nii')
    data_concatenation = file_0.data
    hdr_0 = file_0.hdr
    orientation_file_0 = get_orientation(file_0)
    if len(list_fname_labels) > 0:
       for i in range(0, len(list_fname_labels)):
            orientation_file_temp = get_orientation(file_labels[i], filename=True)
            if orientation_file_0 != orientation_file_temp :
                print 'ERROR: The files ', fname_in, ' and ', file_labels[i], ' are not in the same orientation. Use sct_image -setorient to change the orientation of a file.'
                sys.exit(2)
            file_temp = load(file_labels[i])
            data_temp = file_temp.get_data()
            data_concatenation = data_concatenation + data_temp

    # Save concatenation as a file
    print '\nWrite NIFTI volumes...'
    img = Nifti1Image(data_concatenation, None, hdr_0)
    save(img, 'concatenation_file.nii.gz')

    # Applying nurbs to the concatenation and save file as binary file
    fname_output = extract_centerline('concatenation_file.nii.gz', remove_temp_files = remove_temp_files, verbose = verbose, algo_fitting=param.algo_fitting, type_window=param.type_window, window_length=param.window_length)

    # Rename files after processing
    if output_file_name != None:
       output_file_name = output_file_name
    else : output_file_name = 'generated_centerline.nii.gz'

    os.rename(fname_output, output_file_name)
    path_binary, file_binary, ext_binary = sct.extract_fname(output_file_name)
    os.rename('concatenation_file_centerline.txt', file_binary+'.txt')

    # Process for a binary file as output:
    sct.run('cp '+output_file_name+' ../')

    # Process for a text file as output:
    sct.run('cp '+file_binary+ '.txt'+ ' ../')

    os.chdir('../')
    # Remove temporary files
    if remove_temp_files:
       print('\nRemove temporary files...')
       sct.run('rm -rf '+path_tmp)