def get_parser():
    parser = SCTArgumentParser(
        description=
        'Compute the Hausdorff\'s distance between two binary images which can be thinned (ie skeletonized).'
        ' If only one image is inputted, it will be only thinned')

    mandatoryArguments = parser.add_argument_group("\nMANDATORY ARGUMENTS")
    mandatoryArguments.add_argument(
        "-i",
        required=True,
        help=
        'First Image on which you want to find the skeleton Example: t2star_manual_gmseg.nii.gz',
        metavar=Metavar.file,
    )

    optional = parser.add_argument_group("\nOPTIONAL ARGUMENTS")
    optional.add_argument("-h",
                          "--help",
                          action="help",
                          help="show this help message and exit")
    optional.add_argument(
        "-d",
        help=
        'Second Image on which you want to find the skeleton Example: t2star_manual_gmseg.nii.gz',
        metavar=Metavar.file,
        required=False,
        default=None)
    optional.add_argument(
        "-thinning",
        type=int,
        help=
        "Thinning : find the skeleton of the binary images using the Zhang-Suen algorithm (1984) and use it to "
        "compute the hausdorff's distance",
        required=False,
        default=1,
        choices=(0, 1))
    optional.add_argument("-resampling",
                          type=float,
                          help="pixel size in mm to resample to Example: 0.5",
                          metavar=Metavar.float,
                          required=False,
                          default=0.1)
    optional.add_argument(
        "-o",
        help='Name of the output file Example: my_hausdorff_dist.txt',
        metavar=Metavar.str,
        required=False,
        default='hausdorff_distance.txt')
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help=
        "Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )

    return parser
Exemple #2
0
def get_parser():
    parser = SCTArgumentParser(description="Download binaries from the web.")
    mandatory = parser.add_argument_group("\nMANDATORY ARGUMENTS")
    mandatory.add_argument('-d',
                           required=True,
                           choices=list(DICT_URL.keys()),
                           help=f"Name of the dataset.")
    optional = parser.add_argument_group("\nOPTIONAL ARGUMENTS")
    optional.add_argument("-h",
                          "--help",
                          action="help",
                          help="Show this help message and exit.")
    optional.add_argument(
        '-o',
        metavar=Metavar.folder,
        action=ActionCreateFolder,
        help="R|Path to a directory to save the downloaded data.\n"
        "(Defaults to ./${dataset-name}. Directory will be created if it does not exist. Warning: existing "
        "data in the directory will be erased unless -k is provided.)\n")
    optional.add_argument('-k',
                          action="store_true",
                          help="Keep existing data in destination directory.")
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help=
        "Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )

    return parser
Exemple #3
0
def get_parser():
    parser = SCTArgumentParser(
        description=
        'Function to compute the Ernst Angle. For examples of T1 values in the brain, see Wansapura et al. '
        'NMR relaxation times in the human brain at 3.0 tesla. Journal of magnetic resonance imaging : '
        'JMRI (1999) vol. 9 (4) pp. 531-8. \nT1 in WM: 832ms\nT1 in GM: 1331ms'
    )

    mandatoryArguments = parser.add_argument_group("\nMANDATORY ARGUMENTS")
    mandatoryArguments.add_argument(
        "-tr",
        type=float,
        required=True,
        help='Value of TR (in ms) to get the Ernst Angle. Example: 2000',
        metavar=Metavar.float,
    )

    optional = parser.add_argument_group("\nOPTIONAL ARGUMENTS")
    optional.add_argument("-h",
                          "--help",
                          action="help",
                          help="Show this help message and exit")
    optional.add_argument("-t1",
                          type=float,
                          help='T1 value (in ms). Example: 832.3',
                          required=False,
                          metavar=Metavar.float,
                          default=832.0)
    optional.add_argument(
        "-b",
        type=float,
        nargs='*',
        metavar=Metavar.float,
        help=
        'Min/Max range of TR (in ms) separated with space. Only use with -v 2. Example: 500 3500',
        required=False)
    optional.add_argument(
        "-o",
        help="Name of the output file containing Ernst angle result.",
        required=False,
        metavar=Metavar.str,
        default="ernst_angle.txt")
    optional.add_argument("-ofig",
                          help="Name of the output graph. Only use with -v 2.",
                          required=False,
                          metavar=Metavar.str,
                          default="ernst_angle.png")
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help=
        "Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )

    return parser
Exemple #4
0
def get_parser():
    # Initialize the parser

    parser = SCTArgumentParser(description='Merge images to the same space')
    mandatory = parser.add_argument_group("MANDATORY ARGUMENTS")
    mandatory.add_argument("-i",
                           metavar=Metavar.file,
                           nargs="+",
                           help="Input images",
                           required=True)
    mandatory.add_argument("-d",
                           metavar=Metavar.file,
                           help="Destination image",
                           required=True)
    mandatory.add_argument(
        "-w",
        nargs="+",
        metavar=Metavar.file,
        help="List of warping fields from input images to destination image",
        required=True)
    optional = parser.add_argument_group("OPTIONAL ARGUMENTS")
    optional.add_argument("-h",
                          "--help",
                          action="help",
                          help="Show this help message and exit")
    optional.add_argument(
        "-x",
        metavar=Metavar.str,
        help=
        "Interpolation for warping the input images to the destination image. Default is linear",
        required=False,
        default=Param().interp)
    optional.add_argument("-o",
                          metavar=Metavar.file,
                          help="Output image",
                          required=False,
                          default=Param().fname_out)

    misc = parser.add_argument_group('MISC')
    misc.add_argument("-r",
                      type=bool,
                      help='Remove temporary files.',
                      required=False,
                      default=Param().rm_tmp,
                      choices=(0, 1))
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help=
        "Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )

    return parser
def get_parser():
    # Initialize the parser

    parser = SCTArgumentParser(
        description=
        'Concatenate transformations. This function is a wrapper for isct_ComposeMultiTransform (ANTs). '
        'The order of input warping fields is important. For example, if you want to concatenate: '
        'A->B and B->C to yield A->C, then you have to input warping fields in this order: A->B B->C.',
    )

    mandatoryArguments = parser.add_argument_group("\nMANDATORY ARGUMENTS")
    mandatoryArguments.add_argument(
        "-d",
        required=True,
        help='Destination image. (e.g. "mt.nii.gz")',
        metavar=Metavar.file,
    )
    mandatoryArguments.add_argument(
        "-w",
        required=True,
        help=
        'Transformation(s), which can be warping fields (nifti image) or affine transformation matrix (text '
        'file). Separate with space. Example: warp1.nii.gz warp2.nii.gz',
        nargs='+',
        metavar=Metavar.file)

    optional = parser.add_argument_group("\nOPTIONAL ARGUMENTS")
    optional.add_argument(
        "-winv",
        help=
        'Affine transformation(s) listed in flag -w which should be inverted before being used. Note that this '
        'only concerns affine transformation (not warping fields). If you would like to use an inverse warping'
        'field, then directly input the inverse warping field in flag -w.',
        nargs='*',
        metavar=Metavar.file,
        default=[])
    optional.add_argument("-h",
                          "--help",
                          action="help",
                          help="show this help message and exit")
    optional.add_argument(
        "-o",
        help='Name of output warping field (e.g. "warp_template2mt.nii.gz")',
        metavar=Metavar.str)
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help=
        "Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )

    return parser
Exemple #6
0
def get_parser():
    parser = SCTArgumentParser(
        description=
        'Check the installation and environment variables of the toolbox and its dependencies.'
    )

    optional = parser.add_argument_group("\nOPTIONAL ARGUMENTS")
    optional.add_argument("-h",
                          "--help",
                          action="help",
                          help="Show this help message and exit")
    optional.add_argument('-complete',
                          help="Complete test.",
                          action="store_true")
    optional.add_argument(
        "-short",
        help="Short test. Only shows SCT version, CPU cores and RAM available.",
        action="store_true")

    return parser
def get_parser():
    parser = SCTArgumentParser(
        description='Detection of the Ponto-Medullary Junction (PMJ). '
        'This method is based on a machine-learning algorithm published in (Gros et al. 2018, Medical '
        'Image Analysis, https://doi.org/10.1016/j.media.2017.12.001). Two models are available: one for '
        'T1w-like and another for T2w-like images. '
        'If the PMJ is detected from the input image, a NIfTI mask is output '
        '("*_pmj.nii.gz") with one voxel (value=50) located at the predicted PMJ '
        'position. If the PMJ is not detected, nothing is output.')

    mandatory = parser.add_argument_group("\nMANDATORY ARGUMENTS")
    mandatory.add_argument(
        "-i",
        required=True,
        metavar=Metavar.file,
        help='Input image. Example: t2.nii.gz',
    )
    mandatory.add_argument(
        "-c",
        choices=("t1", "t2"),
        required=True,
        help=
        "Type of image contrast, if your contrast is not in the available options (t1, t2), "
        "use t1 (cord bright/ CSF dark) or t2 (cord dark / CSF bright)",
    )
    optional = parser.add_argument_group("\nOPTIONAL ARGUMENTS")
    optional.add_argument("-h",
                          "--help",
                          action="help",
                          help="Show this help message and exit")
    optional.add_argument(
        "-s",
        metavar=Metavar.file,
        help='SC segmentation or centerline mask. '
        'Provide this mask helps the detection of the PMJ by indicating the position of the SC '
        'in the Right-to-Left direction. Example: t2_seg.nii.gz',
        required=False)
    optional.add_argument("-ofolder",
                          metavar=Metavar.folder,
                          help='Output folder. Example: My_Output_Folder',
                          action=ActionCreateFolder,
                          required=False)
    optional.add_argument('-o',
                          metavar=Metavar.file,
                          help='Output filename. Example: pmj.nii.gz '),
    optional.add_argument(
        '-qc',
        metavar=Metavar.str,
        help=
        'The path where the quality control generated content will be saved.',
        default=None)
    optional.add_argument("-igt",
                          metavar=Metavar.str,
                          help="File name of ground-truth PMJ (single voxel).",
                          required=False)
    optional.add_argument("-r",
                          type=int,
                          help="Remove temporary files.",
                          required=False,
                          default=1,
                          choices=(0, 1))
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help=
        "Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )

    return parser
def get_parser():
    """
    :return: Returns the parser with the command line documentation contained in it.
    """
    # Initialize the parser
    parser = SCTArgumentParser(description=(
        "Compute the following morphometric measures based on the spinal cord segmentation:\n"
        "  - area [mm^2]: Cross-sectional area, measured by counting pixels in each slice. Partial volume can be "
        "accounted for by inputing a mask comprising values within [0,1].\n"
        "  - angle_AP, angle_RL: Estimated angle between the cord centerline and the axial slice. This angle is "
        "used to correct for morphometric information.\n"
        "  - diameter_AP, diameter_RL: Finds the major and minor axes of the cord and measure their length.\n"
        "  - eccentricity: Eccentricity of the ellipse that has the same second-moments as the spinal cord. "
        "The eccentricity is the ratio of the focal distance (distance between focal points) over the major axis "
        "length. The value is in the interval [0, 1). When it is 0, the ellipse becomes a circle.\n"
        "  - orientation: angle (in degrees) between the AP axis of the spinal cord and the AP axis of the "
        "image\n"
        "  - solidity: CSA(spinal_cord) / CSA_convex(spinal_cord). If perfect ellipse, it should be one. This "
        "metric is interesting for detecting non-convex shape (e.g., in case of strong compression)\n"
        "  - length: Length of the segmentation, computed by summing the slice thickness (corrected for the "
        "centerline angle at each slice) across the specified superior-inferior region.\n"
    ))

    mandatory = parser.add_argument_group("\nMANDATORY ARGUMENTS")
    mandatory.add_argument(
        '-i',
        metavar=Metavar.file,
        required=True,
        help=
        "Mask to compute morphometrics from. Could be binary or weighted. E.g., spinal cord segmentation."
        "Example: seg.nii.gz")

    optional = parser.add_argument_group("\nOPTIONAL ARGUMENTS")
    optional.add_argument("-h",
                          "--help",
                          action="help",
                          help="Show this help message and exit.")
    optional.add_argument(
        '-o',
        metavar=Metavar.file,
        help="Output file name (add extension). Default: csa.csv.")
    optional.add_argument(
        '-append',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1],
        default=0,
        help=
        "Append results as a new line in the output csv file instead of overwriting it."
    )
    optional.add_argument(
        '-z',
        metavar=Metavar.str,
        type=str,
        help=
        "Slice range to compute the metrics across (requires '-p csa'). Example: 5:23"
    )
    optional.add_argument(
        '-perslice',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1],
        default=0,
        help=
        "Set to 1 to output one metric per slice instead of a single output metric. Please note that when "
        "methods ml or map is used, outputing a single metric per slice and then averaging them all is not the "
        "same as outputting a single metric at once across all slices.")
    optional.add_argument(
        '-vert',
        metavar=Metavar.str,
        help=
        "Vertebral levels to compute the metrics across. Example: 2:9 for C2 to T2."
    )
    optional.add_argument(
        '-vertfile',
        metavar=Metavar.str,
        default='./label/template/PAM50_levels.nii.gz',
        help="R|Vertebral labeling file. Only use with flag -vert.\n"
        "The input and the vertebral labelling file must in the same voxel coordinate system "
        "and must match the dimensions between each other. ")
    optional.add_argument(
        '-perlevel',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1],
        default=0,
        help=
        "Set to 1 to output one metric per vertebral level instead of a single output metric. This flag needs "
        "to be used with flag -vert.")
    optional.add_argument(
        '-r',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1],
        default=1,
        help=
        "Removes temporary folder used for the algorithm at the end of execution."
    )
    optional.add_argument(
        '-angle-corr',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1],
        default=1,
        help=
        "Angle correction for computing morphometric measures. When angle correction is used, the cord within "
        "the slice is stretched/expanded by a factor corresponding to the cosine of the angle between the "
        "centerline and the axial plane. If the cord is already quasi-orthogonal to the slab, you can set "
        "-angle-corr to 0.")
    optional.add_argument(
        '-centerline-algo',
        choices=['polyfit', 'bspline', 'linear', 'nurbs'],
        default='bspline',
        help=
        "Algorithm for centerline fitting. Only relevant with -angle-corr 1.")
    optional.add_argument(
        '-centerline-smooth',
        metavar=Metavar.int,
        type=int,
        default=30,
        help=
        "Degree of smoothing for centerline fitting. Only use with -centerline-algo {bspline, linear}."
    )
    optional.add_argument(
        '-qc',
        metavar=Metavar.folder,
        action=ActionCreateFolder,
        help=
        "The path where the quality control generated content will be saved.")
    optional.add_argument(
        '-qc-dataset',
        metavar=Metavar.str,
        help=
        "If provided, this string will be mentioned in the QC report as the dataset the process was run on."
    )
    optional.add_argument(
        '-qc-subject',
        metavar=Metavar.str,
        help=
        "If provided, this string will be mentioned in the QC report as the subject the process was run on."
    )
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help=
        "Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )

    return parser
def get_parser():
    parser = SCTArgumentParser(
        description=
        'Extraction of grey level co-occurence matrix (GLCM) texture features from an image within a given '
        'mask. The textures features are those defined in the sckit-image implementation: '
        'http://scikit-image.org/docs/dev/api/skimage.feature.html#greycoprops. This function outputs '
        'one nifti file per texture metric (' + ParamGLCM().feature +
        ') and per orientation called '
        'fnameInput_feature_distance_angle.nii.gz. Also, a file averaging each metric across the angles, '
        'called fnameInput_feature_distance_mean.nii.gz, is output.')

    mandatoryArguments = parser.add_argument_group("\nMANDATORY ARGUMENTS")
    mandatoryArguments.add_argument(
        "-i",
        required=True,
        help='Image to analyze. Example: t2.nii.gz',
        metavar=Metavar.file,
    )
    mandatoryArguments.add_argument(
        "-m",
        required=True,
        metavar=Metavar.file,
        help='Image mask Example: t2_seg.nii.gz',
    )

    optional = parser.add_argument_group("\nOPTIONALS ARGUMENTS")
    optional.add_argument("-h",
                          "--help",
                          action="help",
                          help="Show this help message and exit")
    optional.add_argument(
        "-feature",
        metavar=Metavar.str,
        help='List of GLCM texture features (separate arguments with ",").',
        required=False,
        default=ParamGLCM().feature)
    optional.add_argument(
        "-distance",
        metavar=Metavar.int,
        help=
        'Distance offset for GLCM computation, in pixel (suggested distance values between 1 and 5). Example: 1',
        required=False,
        default=ParamGLCM().distance)
    optional.add_argument(
        "-angle",
        metavar=Metavar.list,
        help=
        'List of angles for GLCM computation, separate arguments with ",", in degrees (suggested distance values '
        'between 0 and 179). Example: 0,90',
        required=False,
        default=ParamGLCM().angle)
    optional.add_argument(
        "-dim",
        help=
        "Compute the texture on the axial (ax), sagittal (sag) or coronal (cor) slices.",
        required=False,
        choices=('ax', 'sag', 'cor'),
        default=Param().dim)
    optional.add_argument("-ofolder",
                          metavar=Metavar.folder,
                          help='Output folder. Example: /my_texture/',
                          action=ActionCreateFolder,
                          required=False,
                          default=Param().path_results)
    optional.add_argument("-igt",
                          metavar=Metavar.str,
                          help="File name of ground-truth texture metrics.",
                          required=False)
    optional.add_argument("-r",
                          help="Remove temporary files.",
                          required=False,
                          type=int,
                          choices=(0, 1),
                          default=int(Param().rm_tmp))
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help=
        "Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )

    return parser
def get_parser():
    # Initialize default parameters
    param_default = Param()

    parser = SCTArgumentParser(description='Create mask along z direction.')

    mandatoryArguments = parser.add_argument_group("\nMANDATORY ARGUMENTS")
    mandatoryArguments.add_argument(
        '-i',
        required=True,
        help=
        'Image to create mask on. Only used to get header. Must be 3D. Example: data.nii.gz',
        metavar=Metavar.file,
    )
    mandatoryArguments.add_argument(
        '-p',
        default=param_default.process,
        required=True,
        help='R|Process to generate mask.\n'
        '  <coord,XxY>: Center mask at the X,Y coordinates. (e.g. "coord,20x15")\n'
        '  <point,FILE>: Center mask at the X,Y coordinates of the label defined in input volume FILE. (e.g. "point,label.nii.gz")\n'
        '  <center>: Center mask in the middle of the FOV (nx/2, ny/2).\n'
        '  <centerline,FILE>: At each slice, the mask is centered at the spinal cord centerline, defined by the input segmentation FILE. (e.g. "centerline,t2_seg.nii.gz")',
        metavar=Metavar.str,
    )

    optional = parser.add_argument_group("\nOPTIONAL ARGUMENTS")
    optional.add_argument("-h",
                          "--help",
                          action="help",
                          help="Show this help message and exit")
    optional.add_argument(
        '-size',
        help=
        'Size of the mask in the axial plane, given in pixel (Example: 35) or in millimeter (Example: 35mm). '
        'If shape=gaussian, size corresponds to "sigma" (Example: 45).',
        metavar=Metavar.str,
        required=False,
        default=param_default.size)
    optional.add_argument('-f',
                          help='Shape of the mask',
                          required=False,
                          default=param_default.shape,
                          choices=('cylinder', 'box', 'gaussian'))
    optional.add_argument('-o',
                          metavar=Metavar.str,
                          help='Name of output mask, Example: data.nii',
                          required=False)
    optional.add_argument("-r",
                          type=int,
                          help='Remove temporary files',
                          required=False,
                          default=1,
                          choices=(0, 1))
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help=
        "Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )

    return parser
def get_parser():
    parser = SCTArgumentParser(
        description="Segment an anatomical structure or pathologies according to the specified deep learning model."
    )

    input_output = parser.add_argument_group("\nINPUT/OUTPUT")
    input_output.add_argument(
        "-i",
        nargs="+",
        help="Image to segment. Can be multiple images (separated with space).",
        metavar=Metavar.file)
    input_output.add_argument(
        "-c",
        nargs="+",
        help="Type of image contrast. Indicates the order in which the images have been presented with -i. "
             "Optional if only one image is specified with -i. The contrasts should be separated by spaces "
             "(e.g., -c t1 t2).",
        choices=('t1', 't2', 't2star'),
        metavar=Metavar.file)
    input_output.add_argument(
        "-o",
        help="Output file name. In case of multi-class segmentation, class-specific suffixes will be added. By default,"
             "suffix '_seg' will be added and output extension will be .nii.gz.",
        metavar=Metavar.str)

    seg = parser.add_argument_group('\nTASKS')
    seg.add_argument(
        "-task",
        nargs="+",
        help="Task to perform. It could either be a pre-installed task, task that could be installed, or a custom task."
             " To list available tasks, run: sct_deepseg -list-tasks. To use a custom task, indicate the path to the "
             " ivadomed packaged model (see https://ivadomed.org/en/latest/pretrained_models.html#packaged-model-format for more details). "
             " More than one path can be indicated (separated with space) for cascaded application of the models.",
        metavar=Metavar.str)
    seg.add_argument(
        "-list-tasks",
        action='store_true',
        help="Display a list of tasks that can be achieved.")
    seg.add_argument(
        "-install-task",
        help="Install models that are required for specified task.",
        choices=list(deepseg.models.TASKS.keys()))

    misc = parser.add_argument_group('\nPARAMETERS')
    misc.add_argument(
        "-thr",
        type=float,
        dest='binarize_prediction',
        help="Binarize segmentation with specified threshold. Set to 0 for no thresholding (i.e., soft segmentation). "
             "Default value is model-specific and was set during optimization "
             "(more info at https://github.com/sct-pipeline/deepseg-threshold).",
        metavar=Metavar.float,
        default=None)
    misc.add_argument(
        "-r",
        type=int,
        help="Remove temporary files.",
        choices=(0, 1),
        default=1)
    misc.add_argument(
        "-largest",
        dest='keep_largest',
        type=int,
        help="Keep the largest connected-objects from the output segmentation. Specify the number of objects to keep."
             "To keep all objects, set to 0",
        default=None)
    misc.add_argument(
        "-fill-holes",
        type=int,
        help="Fill small holes in the segmentation.",
        choices=(0, 1),
        default=None)
    misc.add_argument(
        "-remove-small",
        type=str,
        nargs="+",
        help="Minimal object size to keep with unit (mm3 or vox). A single value can be provided or one value per "
             "prediction class. Single value example: 1mm3, 5vox. Multiple values example: 10 20 10vox (remove objects "
             "smaller than 10 voxels for class 1 and 3, and smaller than 20 voxels for class 2).",
        default=None)

    misc = parser.add_argument_group('\nMISC')
    misc.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help="Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode")
    misc.add_argument(
        "-h",
        "--help",
        action="help",
        help="Show this help message and exit")

    return parser
Exemple #12
0
def get_parser():

    # initialize parameters
    param_default = ParamMoco(is_diffusion=True, group_size=3, metric='MI', smooth='1')

    parser = SCTArgumentParser(
        description="Motion correction of dMRI data. Some of the features to improve robustness were proposed in Xu et "
                    "al. (http://dx.doi.org/10.1016/j.neuroimage.2012.11.014) and include:\n"
                    "  - group-wise (-g)\n"
                    "  - slice-wise regularized along z using polynomial function (-param). For more info about the "
                    "method, type: isct_antsSliceRegularizedRegistration\n"
                    "  - masking (-m)\n"
                    "  - iterative averaging of target volume\n"
    )

    mandatory = parser.add_argument_group("\nMANDATORY ARGUMENTS")
    mandatory.add_argument(
        '-i',
        metavar=Metavar.file,
        required=True,
        help="Diffusion data. Example: dmri.nii.gz"
    )
    mandatory.add_argument(
        '-bvec',
        metavar=Metavar.file,
        required=True,
        help='Bvecs file. Example: bvecs.txt'
    )

    optional = parser.add_argument_group("\nOPTIONAL ARGUMENTS")
    optional.add_argument(
        "-h",
        "--help",
        action="help",
        help="Show this help message and exit."
    )
    optional.add_argument(
        '-bval',
        metavar=Metavar.file,
        default=param_default.fname_bvals,
        help='Bvals file. Example: bvals.txt',
    )
    optional.add_argument(
        '-bvalmin',
        type=float,
        metavar=Metavar.float,
        default=param_default.bval_min,
        help='B-value threshold (in s/mm2) below which data is considered as b=0. Example: 50.0',
    )
    optional.add_argument(
        '-g',
        type=int,
        metavar=Metavar.int,
        default=param_default.group_size,
        help='Group nvols successive dMRI volumes for more robustness. Example: 2',
    )
    optional.add_argument(
        '-m',
        metavar=Metavar.file,
        default=param_default.fname_mask,
        help='Binary mask to limit voxels considered by the registration metric. Example: dmri_mask.nii.gz',
    )
    optional.add_argument(
        '-param',
        metavar=Metavar.list,
        type=list_type(',', str),
        help=f"Advanced parameters. Assign value with \"=\", and separate arguments with \",\".\n"
             f"  - poly [int]: Degree of polynomial function used for regularization along Z. For no regularization "
             f"set to 0. Default={param_default.poly}.\n"
             f"  - smooth [mm]: Smoothing kernel. Default={param_default.smooth}.\n"
             f"  - metric {{MI, MeanSquares, CC}}: Metric used for registration. Default={param_default.metric}.\n"
             f"  - gradStep [float]: Searching step used by registration algorithm. The higher the more deformation "
             f"allowed. Default={param_default.gradStep}.\n"
             f"  - sample [None or 0-1]: Sampling rate used for registration metric. "
             f"Default={param_default.sampling}.\n"
    )
    optional.add_argument(
        '-x',
        choices=['nn', 'linear', 'spline'],
        default=param_default.interp,
        help="Final interpolation."
    )
    optional.add_argument(
        '-ofolder',
        metavar=Metavar.folder,
        action=ActionCreateFolder,
        default=param_default.path_out,
        help="Output folder. Example: dmri_moco_results"
    )
    optional.add_argument(
        "-r",
        choices=('0', '1'),
        default=param_default.remove_temp_files,
        help="Remove temporary files. 0 = no, 1 = yes"
    )
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help="Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )
    optional.add_argument(
        '-qc',
        metavar=Metavar.folder,
        action=ActionCreateFolder,
        help="The path where the quality control generated content will be saved. (Note: "
             "Both '-qc' and '-qc-seg' are required in order to generate a QC report.)"
    )
    optional.add_argument(
        '-qc-seg',
        metavar=Metavar.file,
        help="Segmentation of spinal cord to improve cropping in qc report. (Note: "
             "Both '-qc' and '-qc-seg' are required in order to generate a QC report.)"
    )
    optional.add_argument(
        '-qc-fps',
        metavar=Metavar.float,
        type=float,
        default=3,
        help="This float number is the number of frames per second for the output gif images."
    )
    optional.add_argument(
        '-qc-dataset',
        metavar=Metavar.str,
        help="If provided, this string will be mentioned in the QC report as the dataset the process was run on."
    )
    optional.add_argument(
        '-qc-subject',
        metavar=Metavar.str,
        help="If provided, this string will be mentioned in the QC report as the subject the process was run on."
    )

    return parser
Exemple #13
0
def get_parser():
    # Initialize the parser
    parser = SCTArgumentParser(description=(
        "This program segments automatically the spinal cord on T1- and T2-weighted images, for any field of view. "
        "You must provide the type of contrast, the image as well as the output folder path. The segmentation "
        "follows the spinal cord centerline, which is provided by an automatic tool: Optic. The initialization of "
        "the segmentation is made on the median slice of the centerline, and can be ajusted using the -init "
        "parameter. The initial radius of the tubular mesh that will be propagated should be adapted to size of "
        "the spinal cord on the initial propagation slice. \n"
        "\n"
        "Primary output is the binary mask of the spinal cord segmentation. This method must provide VTK "
        "triangular mesh of the segmentation (option -mesh). Spinal cord centerline is available as a binary image "
        "(-centerline-binary) or a text file with coordinates in world referential (-centerline-coord).\n"
        "\n"
        "Cross-sectional areas along the spinal cord can be available (-cross). Several tips on segmentation "
        "correction can be found on the 'Correcting sct_propseg' page in the Tutorials section of the "
        "documentation.\n"
        "\n"
        "If the segmentation fails at some location (e.g. due to poor contrast between spinal cord and CSF), edit "
        "your anatomical image (e.g. with fslview) and manually enhance the contrast by adding bright values "
        "around the spinal cord for T2-weighted images (dark values for T1-weighted). Then, launch the "
        "segmentation again.\n"
        "\n"
        "References:\n"
        "  - [De Leener B, Kadoury S, Cohen-Adad J. Robust, accurate and fast automatic segmentation of the spinal "
        "cord. Neuroimage 98, 2014. pp 528-536. DOI: 10.1016/j.neuroimage.2014.04.051](https://pubmed.ncbi.nlm.nih.gov/24780696/)\n"
        "  - [De Leener B, Cohen-Adad J, Kadoury S. Automatic segmentation of the spinal cord and spinal canal "
        "coupled with vertebral labeling. IEEE Trans Med Imaging. 2015 Aug;34(8):1705-18.](https://pubmed.ncbi.nlm.nih.gov/26011879/)"
    ))

    mandatory = parser.add_argument_group("\nMANDATORY ARGUMENTS")
    mandatory.add_argument('-i',
                           metavar=Metavar.file,
                           required=True,
                           help="Input image. Example: ti.nii.gz")
    mandatory.add_argument(
        '-c',
        choices=['t1', 't2', 't2s', 'dwi'],
        required=True,
        help=
        "Type of image contrast. If your contrast is not in the available options (t1, t2, t2s, dwi), use "
        "t1 (cord bright / CSF dark) or t2 (cord dark / CSF bright)")

    optional = parser.add_argument_group("\nOPTIONAL ARGUMENTS")
    optional.add_argument("-h",
                          "--help",
                          action="help",
                          help="Show this help message and exit.")
    optional.add_argument('-o',
                          metavar=Metavar.file,
                          help='Output filename. Example: spinal_seg.nii.gz ')
    optional.add_argument('-down',
                          metavar=Metavar.int,
                          type=int,
                          help="Down limit of the propagation. Default is 0.")
    optional.add_argument(
        '-up',
        metavar=Metavar.int,
        type=int,
        help=
        "Up limit of the propagation. Default is the highest slice of the image."
    )
    optional.add_argument(
        '-r',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1],
        default=1,
        help="Whether to remove temporary files. 0 = no, 1 = yes")
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help=
        "Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )
    optional.add_argument('-mesh',
                          action="store_true",
                          help="Output: mesh of the spinal cord segmentation")
    optional.add_argument('-centerline-binary',
                          action="store_true",
                          help="Output: centerline as a binary image.")
    optional.add_argument('-CSF',
                          action="store_true",
                          help="Output: CSF segmentation.")
    optional.add_argument('-centerline-coord',
                          action="store_true",
                          help="Output: centerline in world coordinates.")
    optional.add_argument('-cross',
                          action="store_true",
                          help="Output: cross-sectional areas.")
    optional.add_argument('-init-tube',
                          action="store_true",
                          help="Output: initial tubular meshes.")
    optional.add_argument('-low-resolution-mesh',
                          action="store_true",
                          help="Output: low-resolution mesh.")
    optional.add_argument(
        '-init-centerline',
        metavar=Metavar.file,
        help=
        "R|Filename of centerline to use for the propagation. Use format .txt or .nii; see file structure in "
        "documentation.\n"
        "Replace filename by 'viewer' to use interactive viewer for providing centerline. Example: "
        "-init-centerline viewer")
    optional.add_argument(
        '-init',
        metavar=Metavar.float,
        type=float,
        help=
        "Axial slice where the propagation starts, default is middle axial slice."
    )
    optional.add_argument(
        '-init-mask',
        metavar=Metavar.file,
        help=
        "R|Mask containing three center of the spinal cord, used to initiate the propagation.\n"
        "Replace filename by 'viewer' to use interactive viewer for providing mask. Example: -init-mask viewer"
    )
    optional.add_argument(
        '-mask-correction',
        metavar=Metavar.file,
        help=
        "mask containing binary pixels at edges of the spinal cord on which the segmentation algorithm will be "
        "forced to register the surface. Can be used in case of poor/missing contrast between spinal cord and "
        "CSF or in the presence of artefacts/pathologies.")
    optional.add_argument(
        '-rescale',
        metavar=Metavar.float,
        type=float,
        default=1.0,
        help=
        "Rescale the image (only the header, not the data) in order to enable segmentation on spinal cords with "
        "dimensions different than that of humans (e.g., mice, rats, elephants, etc.). For example, if the "
        "spinal cord is 2x smaller than that of human, then use -rescale 2")
    optional.add_argument(
        '-radius',
        metavar=Metavar.float,
        type=float,
        help="Approximate radius (in mm) of the spinal cord. Default is 4.")
    optional.add_argument(
        '-nbiter',
        metavar=Metavar.int,
        type=int,
        help=
        "Stop condition (affects only the Z propogation): number of iteration for the propagation for both "
        "direction. Default is 200.")
    optional.add_argument(
        '-max-area',
        metavar=Metavar.float,
        type=float,
        help=
        "[mm^2], stop condition (affects only the Z propogation): maximum cross-sectional area. Default is 120."
    )
    optional.add_argument(
        '-max-deformation',
        metavar=Metavar.float,
        type=float,
        help=
        "[mm], stop condition (affects only the Z propogation): maximum deformation per iteration. Default is "
        "2.5")
    optional.add_argument(
        '-min-contrast',
        metavar=Metavar.float,
        type=float,
        help=
        "[intensity value], stop condition (affects only the Z propogation): minimum local SC/CSF contrast, "
        "default is 50")
    optional.add_argument(
        '-d',
        metavar=Metavar.float,
        type=float,
        help=
        "trade-off between distance of most promising point (d is high) and feature strength (d is low), "
        "default depend on the contrast. Range of values from 0 to 50. 15-25 values show good results. Default "
        "is 10.")
    optional.add_argument(
        '-distance-search',
        metavar=Metavar.float,
        type=float,
        help=
        "maximum distance of optimal points computation along the surface normals. Range of values from 0 to 30. "
        "Default is 15")
    optional.add_argument(
        '-alpha',
        metavar=Metavar.float,
        type=float,
        help=
        "Trade-off between internal (alpha is high) and external (alpha is low) forces. Range of values from 0 "
        "to 50. Default is 25.")
    optional.add_argument(
        '-qc',
        metavar=Metavar.folder,
        action=ActionCreateFolder,
        help=
        "The path where the quality control generated content will be saved.")
    optional.add_argument(
        '-qc-dataset',
        metavar=Metavar.str,
        help=
        "If provided, this string will be mentioned in the QC report as the dataset the process was run on."
    )
    optional.add_argument(
        '-qc-subject',
        metavar=Metavar.str,
        help=
        "If provided, this string will be mentioned in the QC report as the subject the process was run on."
    )
    optional.add_argument(
        '-correct-seg',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1],
        default=1,
        help=
        "Enable (1) or disable (0) the algorithm that checks and correct the output segmentation. More "
        "specifically, the algorithm checks if the segmentation is consistent with the centerline provided by "
        "isct_propseg.")
    optional.add_argument('-igt',
                          metavar=Metavar.file,
                          help="File name of ground-truth segmentation.")

    return parser
Exemple #14
0
def get_parser():
    # Initialize default parameters
    param_default = Param()
    parser = SCTArgumentParser(
        description=
        "This function warps the template and all atlases to a destination image."
    )

    mandatory = parser.add_argument_group("\nMANDATORY ARGUMENTS")
    mandatory.add_argument(
        '-d',
        metavar=Metavar.file,
        required=True,
        help=
        "Destination image the template will be warped to. Example: dwi_mean.nii.gz"
    )
    mandatory.add_argument(
        '-w',
        metavar=Metavar.file,
        required=True,
        help="Warping field. Example: warp_template2dmri.nii.gz")

    optional = parser.add_argument_group("\nOPTIONAL ARGUMENTS")
    optional.add_argument("-h",
                          "--help",
                          action="help",
                          help="Show this help message and exit.")
    optional.add_argument('-a',
                          metavar=Metavar.int,
                          type=int,
                          choices=[0, 1],
                          default=param_default.warp_atlas,
                          help="Warp atlas of white matter.")
    optional.add_argument('-s',
                          metavar=Metavar.int,
                          type=int,
                          choices=[0, 1],
                          default=param_default.warp_spinal_levels,
                          help="Warp spinal levels.")
    optional.add_argument('-ofolder',
                          metavar=Metavar.folder,
                          action=ActionCreateFolder,
                          default=param_default.folder_out,
                          help="Name of output folder.")
    optional.add_argument('-t',
                          metavar=Metavar.folder,
                          default=str(param_default.path_template),
                          help="Path to template.")
    optional.add_argument(
        '-qc',
        metavar=Metavar.folder,
        action=ActionCreateFolder,
        default=param_default.path_qc,
        help=
        "The path where the quality control generated content will be saved.")
    optional.add_argument(
        '-qc-dataset',
        metavar=Metavar.str,
        help=
        "If provided, this string will be mentioned in the QC report as the dataset the process was run on."
    )
    optional.add_argument(
        '-qc-subject',
        metavar=Metavar.str,
        help=
        "If provided, this string will be mentioned in the QC report as the subject the process was run on."
    )
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help=
        "Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )

    return parser
Exemple #15
0
def get_parser():
    parser = SCTArgumentParser(
        description=
        'Perform manipulations on images (e.g., pad, change space, split along dimension). '
        'Inputs can be a number, a 4d image, or several 3d images separated with ","'
    )

    mandatory = parser.add_argument_group('MANDATORY ARGUMENTS')
    mandatory.add_argument(
        '-i',
        nargs='+',
        metavar=Metavar.file,
        help=
        'Input file(s). If several inputs: separate them by white space. Example: "data.nii.gz"',
        required=True)
    optional = parser.add_argument_group('OPTIONAL ARGUMENTS')
    optional.add_argument('-h',
                          '--help',
                          action='help',
                          help='Show this help message and exit')
    optional.add_argument('-o',
                          metavar=Metavar.file,
                          help='Output file. Example: data_pad.nii.gz',
                          required=False)

    image = parser.add_argument_group('IMAGE OPERATIONS')
    image.add_argument(
        '-pad',
        metavar=Metavar.list,
        help=
        'Pad 3D image. Specify padding as: "x,y,z" (in voxel). Example: "0,0,1"',
        required=False)
    image.add_argument(
        '-pad-asym',
        metavar=Metavar.list,
        help=
        'Pad 3D image with asymmetric padding. Specify padding as: "x_i,x_f,y_i,y_f,z_i,z_f" (in voxel). '
        'Example: "0,0,5,10,1,1"',
        required=False)
    image.add_argument(
        '-split',
        help=
        'Split data along the specified dimension. The suffix _DIM+NUMBER will be added to the intput file name.',
        required=False,
        choices=('x', 'y', 'z', 't'))
    image.add_argument('-concat',
                       help='Concatenate data along the specified dimension',
                       required=False,
                       choices=('x', 'y', 'z', 't'))
    image.add_argument(
        '-remove-vol',
        metavar=Metavar.list,
        help=
        'Remove specific volumes from a 4d volume. Separate with ",". Example: "0,5,10"',
        required=False)
    image.add_argument(
        '-keep-vol',
        metavar=Metavar.list,
        help=
        'Keep specific volumes from a 4d volume (remove others). Separate with ",". Example: "1,2,3,11"',
        required=False)
    image.add_argument('-type',
                       help='Change file type',
                       required=False,
                       choices=('uint8', 'int16', 'int32', 'float32',
                                'complex64', 'float64', 'int8', 'uint16',
                                'uint32', 'int64', 'uint64'))

    header = parser.add_argument_group('HEADER OPERATIONS')
    header.add_argument(
        '-copy-header',
        metavar=Metavar.file,
        help=
        'Copy the header of the source image (specified in -i) to the destination image (specified here) '
        'and save it into a new image (specified in -o)',
        required=False)

    orientation = parser.add_argument_group('ORIENTATION OPERATIONS')
    orientation.add_argument('-getorient',
                             help='Get orientation of the input image',
                             action='store_true',
                             required=False)
    orientation.add_argument(
        '-setorient',
        help='Set orientation of the input image (only modifies the header).',
        choices=
        'RIP LIP RSP LSP RIA LIA RSA LSA IRP ILP SRP SLP IRA ILA SRA SLA RPI LPI RAI LAI RPS LPS RAS LAS PRI PLI ARI ALI PRS PLS ARS ALS IPR SPR IAR SAR IPL SPL IAL SAL PIR PSR AIR ASR PIL PSL AIL ASL'
        .split(),
        required=False)
    orientation.add_argument(
        '-setorient-data',
        help=
        'Set orientation of the input image\'s data (does NOT modify the header, but the data). Use with care !',
        choices=
        'RIP LIP RSP LSP RIA LIA RSA LSA IRP ILP SRP SLP IRA ILA SRA SLA RPI LPI RAI LAI RPS LPS RAS LAS PRI PLI ARI ALI PRS PLS ARS ALS IPR SPR IAR SAR IPL SPL IAL SAL PIR PSR AIR ASR PIL PSL AIL ASL'
        .split(),
        required=False)

    multi = parser.add_argument_group(
        'MULTI-COMPONENT OPERATIONS ON ITK COMPOSITE WARPING FIELDS')
    multi.add_argument(
        '-mcs',
        action='store_true',
        help=
        'Multi-component split: Split ITK warping field into three separate displacement fields. '
        'The suffix _X, _Y and _Z will be added to the input file name.',
        required=False)
    multi.add_argument(
        '-omc',
        action='store_true',
        help=
        'Multi-component merge: Merge inputted images into one multi-component image. Requires several inputs.',
        required=False)

    warping = parser.add_argument_group('WARPING FIELD OPERATIONS:')
    warping.add_argument(
        '-display-warp',
        action='store_true',
        help='Create a grid and deform it using provided warping field.',
        required=False)
    warping.add_argument(
        '-to-fsl',
        metavar=Metavar.file,
        help=
        'Transform displacement field values to absolute FSL warps. To be used with FSL\'s applywarp function with the '
        '`--abs` flag. Input the file that will be used as the input (source) for applywarp and optionally the target '
        '(ref). The target file is necessary for the case where the warp is in a different space than the target. For '
        'example, the inverse warps generated by `sct_straighten_spinalcord`. This feature has not been extensively '
        'validated so consider checking the results of `applywarp` against `sct_apply_transfo` before using in FSL '
        'pipelines. Example syntax: "sct_image -i WARP_SRC2DEST -to-fsl IM_SRC (IM_DEST) -o WARP_FSL", '
        'followed by FSL: "applywarp -i IM_SRC -r IM_DEST -w WARP_FSL --abs -o IM_SRC2DEST" ',
        nargs='*',
        required=False)

    misc = parser.add_argument_group('Misc')
    misc.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help=
        "Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )

    return parser
Exemple #16
0
def get_parser():
    param_default = Param()
    parser = SCTArgumentParser(
        description=
        "Separate b=0 and DW images from diffusion dataset. The output files will have a suffix "
        "(_b0 and _dwi) appended to the input file name.")

    mandatory = parser.add_argument_group("\nMANDATORY ARGUMENTS")
    mandatory.add_argument('-i',
                           metavar=Metavar.file,
                           required=True,
                           help="Diffusion data. Example: dmri.nii.gz")
    mandatory.add_argument('-bvec',
                           metavar=Metavar.file,
                           required=True,
                           help="Bvecs file. Example: bvecs.txt")

    optional = parser.add_argument_group("\nOPTIONAL ARGUMENTS")
    optional.add_argument("-h",
                          "--help",
                          action="help",
                          help="Show this help message and exit.")
    optional.add_argument('-a',
                          type=int,
                          choices=(0, 1),
                          default=param_default.average,
                          help="Average b=0 and DWI data. 0 = no, 1 = yes")
    optional.add_argument(
        '-bval',
        metavar=Metavar.file,
        default="",
        help=
        'bvals file. Used to identify low b-values (in case different from 0). Example: bvals.nii.gz',
    )
    optional.add_argument(
        '-bvalmin',
        type=float,
        metavar=Metavar.float,
        help=
        'B-value threshold (in s/mm2) below which data is considered as b=0. Example: 50.0',
    )
    optional.add_argument(
        '-ofolder',
        metavar=Metavar.folder,
        action=ActionCreateFolder,
        default='./',
        help='Output folder. Example: dmri_separate_results/',
    )
    optional.add_argument("-r",
                          choices=('0', '1'),
                          default=param_default.remove_temp_files,
                          help="Remove temporary files. 0 = no, 1 = yes")
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help=
        "Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )
    return parser
def get_parser():
    parser = SCTArgumentParser(
        description=
        'R|Compute statistics on segmented lesions. The function assigns an ID value to each lesion (1, 2, '
        '3, etc.) and then outputs morphometric measures for each lesion:\n'
        '- volume [mm^3]\n'
        '- length [mm]: length along the Superior-Inferior axis\n'
        '- max_equivalent_diameter [mm]: maximum diameter of the lesion, when approximating\n'
        '                                the lesion as a circle in the axial plane.\n\n'
        'If the proportion of lesion in each region (e.g. WM and GM) does not sum up to 100%, it means '
        'that the registered template does not fully cover the lesion. In that case you might want to '
        'check the registration results.')

    mandatory_arguments = parser.add_argument_group("\nMANDATORY ARGUMENTS")
    mandatory_arguments.add_argument(
        "-m",
        required=True,
        help='Binary mask of lesions (lesions are labeled as "1").',
        metavar=Metavar.file,
    )
    mandatory_arguments.add_argument(
        "-s",
        required=True,
        help=
        "Spinal cord centerline or segmentation file, which will be used to correct morphometric measures with "
        "cord angle with respect to slice. (e.g.'t2_seg.nii.gz')",
        metavar=Metavar.file)

    optional = parser.add_argument_group("\nOPTIONAL ARGUMENTS")
    optional.add_argument("-h",
                          "--help",
                          action="help",
                          help="show this help message and exit")
    optional.add_argument(
        "-i",
        help=
        'Image from which to extract average values within lesions (e.g. "t2.nii.gz"). If provided, the function '
        'computes the mean and standard deviation values of this image within each lesion.',
        metavar=Metavar.file,
        default=None,
        required=False)
    optional.add_argument(
        "-f",
        help=
        "Path to folder containing the atlas/template registered to the anatomical image. If provided, the "
        "function computes: (i) the distribution of each lesion depending on each vertebral level and on each"
        "region of the template (e.g. GM, WM, WM tracts) and (ii) the proportion of ROI (e.g. vertebral level, "
        "GM, WM) occupied by lesion.",
        metavar=Metavar.str,
        default=None,
        required=False)
    optional.add_argument("-ofolder",
                          help='Output folder (e.g. "./")',
                          metavar=Metavar.folder,
                          action=ActionCreateFolder,
                          default='./',
                          required=False)
    optional.add_argument("-r",
                          type=int,
                          help="Remove temporary files.",
                          required=False,
                          default=1,
                          choices=(0, 1))
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help=
        "Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )

    return parser
Exemple #18
0
def get_parser():

    param_default = Param()

    parser = SCTArgumentParser(
        description=(
            f"This program extracts metrics (e.g., DTI or MTR) within labels. Labels could be a single file or "
            f"a folder generated with 'sct_warp_template' containing multiple label files and a label "
            f"description file (info_label.txt). The labels should be in the same space coordinates as the "
            f"input image.\n"
            f"\n"
            f"The labels used by default are taken from the PAM50 template. To learn about the available PAM50 "
            f"white/grey matter atlas labels and their corresponding ID values, please refer to: "
            f"https://spinalcordtoolbox.com/en/latest/overview/concepts/pam50.html#white-and-grey-matter-atlas-pam50-atlas\n"
            f"\n"
            f"To compute FA within labels 0, 2 and 3 within vertebral levels C2 to C7 using binary method:\n"
            f"sct_extract_metric -i dti_FA.nii.gz -l 0,2,3 -vert 2:7 -method bin\n"
            f"\n"
            f"To compute average MTR in a region defined by a single label file (could be binary or 0-1 "
            f"weighted mask) between slices 1 and 4:\n"
            f"sct_extract_metric -i mtr.nii.gz -f "
            f"my_mask.nii.gz -z 1:4 -method wa")
    )
    mandatory = parser.add_argument_group("\nMANDATORY ARGUMENTS")
    mandatory.add_argument(
        '-i',
        metavar=Metavar.file,
        required=True,
        help="Image file to extract metrics from. Example: FA.nii.gz"
    )

    optional = parser.add_argument_group("\nOPTIONAL ARGUMENTS")
    optional.add_argument(
        "-h",
        "--help",
        action="help",
        help="Show this help message and exit."
    )
    optional.add_argument(
        '-f',
        metavar=Metavar.folder,
        default=os.path.join("label", "atlas"),
        help=(f"Single label file, or folder that contains WM tract labels."
              f"Example: {os.path.join(__data_dir__, 'atlas')}")
    )
    optional.add_argument(
        '-l',
        metavar=Metavar.str,
        default='',
        help="Label IDs to extract the metric from. Default = all labels. Separate labels with ','. To select a group "
             "of consecutive labels use ':'. Example: 1:3 is equivalent to 1,2,3. Maximum Likelihood (or MAP) is "
             "computed using all tracts, but only values of the selected tracts are reported."
    )
    optional.add_argument(
        '-list-labels',
        action=_ListLabelsAction,
        nargs=0,
        help="List available labels. These labels are defined in the file 'info_label.txt' located in the folder "
             "specified by the flag '-f'."
    )
    optional.add_argument(
        '-method',
        choices=['ml', 'map', 'wa', 'bin', 'median', 'max'],
        default=param_default.method,
        help="Method to extract metrics.\n"
             "  - ml: maximum likelihood.\n"
             "    This method is recommended for large labels and low noise. Also, this method should only be used"
             " with the PAM50 white/gray matter atlas, or with any custom atlas as long as the sum across all labels"
             " equals 1, in each voxel part of the atlas.\n"
             "  - map: maximum a posteriori.\n"
             "    Mean priors are estimated by maximum likelihood within three clusters"
             " (white matter, gray matter and CSF). Tract and noise variance are set with flag -p."
             " This method should only be used with the PAM50 white/gray matter atlas, or with any custom atlas"
             " as long as the sum across all labels equals 1, in each voxel part of the atlas.\n"
             "  - wa: weighted average\n"
             "  - bin: binarize mask (threshold=0.5)\n"
             "  - median: weighted median.\n"
             "    This implementation of the median treats quantiles as a continuous (vs. discrete) function. For"
             " more details, see https://pypi.org/project/wquantiles/.\n"
             "  - max: for each z-slice of the input data, extract the max value for each slice of the input data."
    )
    optional.add_argument(
        '-append',
        type=int,
        choices=(0, 1),
        default=0,
        help="Whether to append results as a new line in the output csv file instead of overwriting it. 0 = no, 1 = yes"
    )
    optional.add_argument(
        '-combine',
        type=int,
        choices=(0, 1),
        default=0,
        help="Whether to combine multiple labels into a single estimation. 0 = no, 1 = yes"
    )
    optional.add_argument(
        '-o',
        metavar=Metavar.file,
        default=param_default.fname_output,
        help="File name of the output result file collecting the metric estimation results. Include the '.csv' "
             "file extension in the file name. Example: extract_metric.csv"
    )
    optional.add_argument(
        '-output-map',
        metavar=Metavar.file,
        default='',
        help="File name for an image consisting of the atlas labels multiplied by the estimated metric values "
             "yielding the metric value map, useful to assess the metric estimation and especially partial volume "
             "effects."
    )
    optional.add_argument(
        '-z',
        metavar=Metavar.str,
        default=param_default.slices_of_interest,
        help="Slice range to estimate the metric from. First slice is 0. Example: 5:23\n"
             "You can also select specific slices using commas. Example: 0,2,3,5,12'"
    )
    optional.add_argument(
        '-perslice',
        type=int,
        choices=(0, 1),
        default=param_default.perslice,
        help="Whether to output one metric per slice instead of a single output metric. 0 = no, 1 = yes.\n"
             "Please note that when methods ml or map are used, outputting a single metric per slice and then "
             "averaging them all is not the same as outputting a single metric at once across all slices."
    )
    optional.add_argument(
        '-vert',
        metavar=Metavar.str,
        default=param_default.vertebral_levels,
        help="Vertebral levels to estimate the metric across. Example: 2:9 (for C2 to T2)"
    )
    optional.add_argument(
        '-vertfile',
        metavar=Metavar.file,
        default=os.path.join(".", "label", "template", "PAM50_levels.nii.gz"),
        help="Vertebral labeling file. Only use with flag -vert.\n"
             "The input Image and the vertebral labelling file must in the same voxel coordinate system "
             "and must match the dimensions between each other."
    )
    optional.add_argument(
        '-perlevel',
        type=int,
        metavar=Metavar.int,
        default=0,
        help="Whether to output one metric per vertebral level instead of a single output metric. 0 = no, 1 = yes.\n"
             "Please note that this flag needs to be used with the -vert option."
    )
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help="Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )

    advanced = parser.add_argument_group("\nFOR ADVANCED USERS")
    advanced.add_argument(
        '-param',
        metavar=Metavar.str,
        default='',
        help="Advanced parameters for the 'map' method. Separate with comma. All items must be listed (separated "
             "with comma).\n"
             "  - #1: standard deviation of metrics across labels\n"
             "  - #2: standard deviation of the noise (assumed Gaussian)"
    )
    advanced.add_argument(
        '-fix-label',
        metavar=Metavar.list,
        type=list_type(',', str),
        default='',
        help="When using ML or MAP estimations, if you do not want to estimate the metric in one label and fix its "
             "value to avoid effects on other labels, specify <label_ID>,<metric_value. Example: -fix-label 36,0 "
             "(Fix the CSF value)"
    )
    advanced.add_argument(
        '-norm-file',
        metavar=Metavar.file,
        default='',
        help='Filename of the label by which the user wants to normalize.'
    )
    advanced.add_argument(
        '-norm-method',
        choices=['sbs', 'whole'],
        default='',
        help="Method to use for normalization:\n"
             "  - sbs: normalization slice-by-slice\n"
             "  - whole: normalization by the metric value in the whole label for all slices."
    )
    advanced.add_argument(
        '-mask-weighted',
        metavar=Metavar.file,
        default='',
        help="Nifti mask to weight each voxel during ML or MAP estimation. Example: PAM50_wm.nii.gz"
    )
    advanced.add_argument(
        '-discard-neg-val',
        choices=('0', '1'),
        default='0',
        help='Whether to discard voxels with negative value when computing metrics statistics. 0 = no, 1 = yes'
    )

    return parser
Exemple #19
0
def get_parser():
    parser = SCTArgumentParser(
        description=
        "Spinal Cord Segmentation using convolutional networks. Reference: Gros et al. Automatic "
        "segmentation of the spinal cord and intramedullary multiple sclerosis lesions with convolutional "
        "neural networks. Neuroimage. 2019 Jan 1;184:901-915.")
    mandatory = parser.add_argument_group("\nMANDATORY ARGUMENTS")
    mandatory.add_argument(
        "-i",
        required=True,
        metavar=Metavar.file,
        help='Input image. Example: t1.nii.gz',
    )
    mandatory.add_argument(
        "-c",
        required=True,
        help="Type of image contrast.",
        choices=('t1', 't2', 't2s', 'dwi'),
    )

    optional = parser.add_argument_group("\nOPTIONAL ARGUMENTS")
    optional.add_argument("-h",
                          "--help",
                          action="help",
                          help="show this help message and exit")
    optional.add_argument(
        "-centerline",
        help="Method used for extracting the centerline:\n"
        " svm: Automatic detection using Support Vector Machine algorithm.\n"
        " cnn: Automatic detection using Convolutional Neural Network.\n"
        " viewer: Semi-automatic detection using manual selection of a few points with an interactive viewer "
        "followed by regularization.\n"
        " file: Use an existing centerline (use with flag -file_centerline)",
        choices=('svm', 'cnn', 'viewer', 'file'),
        default="svm")
    optional.add_argument(
        "-file_centerline",
        metavar=Metavar.str,
        help=
        'Input centerline file (to use with flag -centerline file). Example: t2_centerline_manual.nii.gz'
    )
    optional.add_argument(
        "-thr",
        type=float,
        help=
        "Binarization threshold (between 0 and 1) to apply to the segmentation prediction. Set to -1 for no "
        "binarization (i.e. soft segmentation output). The default threshold is specific to each contrast and was"
        "estimated using an optimization algorithm. More details at: "
        "https://github.com/sct-pipeline/deepseg-threshold.",
        metavar=Metavar.float,
        default=None)
    optional.add_argument(
        "-brain",
        type=int,
        help=
        'Indicate if the input image contains brain sections (to speed up segmentation). Only use with '
        '"-centerline cnn". (default: 1 for T1/T2 contrasts, 0 for T2*/DWI contrasts)',
        choices=(0, 1))
    optional.add_argument(
        "-kernel",
        help=
        "Choice of kernel shape for the CNN. Segmentation with 3D kernels is slower than with 2D kernels.",
        choices=('2d', '3d'),
        default="2d")
    optional.add_argument("-ofolder",
                          metavar=Metavar.str,
                          help='Output folder. Example: My_Output_Folder ',
                          action=ActionCreateFolder,
                          default=os.getcwd())
    optional.add_argument('-o',
                          metavar=Metavar.file,
                          help='Output filename. Example: spinal_seg.nii.gz '),
    optional.add_argument('-r',
                          type=int,
                          help="Remove temporary files.",
                          choices=(0, 1),
                          default=1)
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help=
        "Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )
    optional.add_argument(
        '-qc',
        metavar=Metavar.str,
        help=
        'The path where the quality control generated content will be saved',
        default=None)
    optional.add_argument(
        '-qc-dataset',
        metavar=Metavar.str,
        help=
        'If provided, this string will be mentioned in the QC report as the dataset the process was run on',
    )
    optional.add_argument(
        '-qc-subject',
        metavar=Metavar.str,
        help=
        'If provided, this string will be mentioned in the QC report as the subject the process was run on',
    )
    optional.add_argument(
        '-igt',
        metavar=Metavar.str,
        help='File name of ground-truth segmentation.',
    )

    return parser
Exemple #20
0
def get_parser():
    parser = SCTArgumentParser(
        description='Compute the Dice Coefficient. '
        'N.B.: indexing (in both time and space) starts with 0 not 1! Inputting -1 for a '
        'size will set it to the full image extent for that dimension.')

    mandatory = parser.add_argument_group("\nMANDATORY ARGUMENTS")
    mandatory.add_argument(
        '-i',
        required=True,
        metavar=Metavar.file,
        help='First input image. Example: t2_seg.nii.gz',
    )
    mandatory.add_argument(
        '-d',
        required=True,
        help='Second input image. Example: t2_manual_seg.nii.gz',
        metavar=Metavar.file,
    )

    optional = parser.add_argument_group("\nOPTIONAL ARGUMENTS")
    optional.add_argument("-h",
                          "--help",
                          action="help",
                          help="Show this help message and exit")
    optional.add_argument(
        '-2d-slices',
        type=int,
        help='Compute DC on 2D slices in the specified dimension',
        required=False,
        choices=(0, 1, 2))
    optional.add_argument(
        '-b',
        metavar=Metavar.list,
        help=
        'Bounding box with the coordinates of the origin and the size of the box as follow: '
        'x_origin,x_size,y_origin,y_size,z_origin,z_size. Example: 5,10,5,10,10,15',
        required=False)
    optional.add_argument(
        '-bmax',
        type=int,
        help='Use maximum bounding box of the images union to compute DC.',
        required=False,
        choices=(0, 1))
    optional.add_argument(
        '-bzmax',
        type=int,
        help=
        'Use maximum bounding box of the images union in the "Z" direction to compute DC.',
        required=False,
        choices=(0, 1))
    optional.add_argument(
        '-bin',
        type=int,
        help='Binarize image before computing DC. (Put non-zero-voxels to 1)',
        required=False,
        choices=(0, 1))
    optional.add_argument(
        '-o',
        metavar=Metavar.str,
        help='Output file with DC results (.txt). Example: dice_coeff.txt',
        required=False)
    optional.add_argument("-r",
                          type=int,
                          help="Remove temporary files.",
                          required=False,
                          default=1,
                          choices=(0, 1))
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help=
        "Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )

    return parser
def get_parser():
    parser = SCTArgumentParser(
        description=
        'Wrapper to processing scripts, which loops across subjects. Subjects should be organized as '
        'folders within a single directory. We recommend following the BIDS convention '
        '(https://bids.neuroimaging.io/). The processing script should accept a subject directory '
        'as its only argument. Additional information is passed via environment variables and the '
        'arguments passed via `-script-args`. If the script or the input data are located within a '
        'git repository, the git commit is displayed. If the script or data have changed since the latest '
        'commit, the symbol "*" is added after the git commit number. If no git repository is found, the '
        'git commit version displays "?!?". The script is copied on the output folder (-path-out).'
    )

    parser.add_argument(
        '-config',
        '-c',
        help=''
        'A json (.json) or yaml (.yml|.yaml) file with arguments. All arguments to the configuration '
        'file are the same as the command line arguments, except all dashes (-) are replaced with '
        'underscores (_). Using command line flags can be used to override arguments provided in '
        'the configuration file, but this is discouraged. Please note that while quotes are optional '
        'for strings in YAML omitting them may cause parse errors.\n' +
        dedent("""
                            Example YAML configuration:
                            path_data   : "~/sct_data"
                            path_output : "~/pipeline_results"
                            script      : "nature_paper_analysis.sh"
                            jobs        : -1\n
                            Example JSON configuration:
                            {
                            "path_data"   : "~/sct_data"
                            "path_output" : "~/pipeline_results"
                            "script"      : "nature_paper_analysis.sh"
                            "jobs"        : -1
                            }\n
                            """))
    parser.add_argument(
        '-jobs',
        type=int,
        default=1,
        help=
        'The number of jobs to run in parallel. Either an integer greater than or equal to one '
        'specifying the number of cores, 0 or a negative integer specifying number of cores minus '
        'that number. For example \'-jobs -1\' will run with all the available cores minus one job in '
        'parallel. Set \'-jobs 0\' to use all available cores.\n'
        'This argument enables process-based parallelism, while \'-itk-threads\' enables thread-based '
        'parallelism. You may need to tweak both to find a balance that works best for your system.',
        metavar=Metavar.int)
    parser.add_argument(
        '-itk-threads',
        type=int,
        default=1,
        help=
        'Sets the environment variable "ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS".\n'
        'Number of threads to use for ITK based programs including ANTs. Increasing this can '
        'provide a performance boost for high-performance (multi-core) computing environments. '
        'However, increasing the number of threads may also result in a large increase in memory.\n'
        'This argument enables thread-based parallelism, while \'-jobs\' enables process-based '
        'parallelism. You may need to tweak both to find a balance that works best for your system.',
        metavar=Metavar.int)
    parser.add_argument(
        '-path-data',
        help='Setting for environment variable: PATH_DATA\n'
        'Path containing subject directories in a consistent format')
    parser.add_argument(
        '-subject-prefix',
        default='sub-',
        help=
        'Subject prefix, defaults to "sub-" which is the prefix used for BIDS directories. '
        'If the subject directories do not share a common prefix, an empty string can be '
        'passed here.')
    parser.add_argument(
        '-path-output',
        default='.',
        help='Base directory for environment variables:\n'
        'PATH_DATA_PROCESSED=' +
        os.path.join('<path-output>', 'data_processed') + '\n'
        'PATH_RESULTS=' + os.path.join('<path-output>', 'results') + '\n'
        'PATH_QC=' + os.path.join('<path-output>', 'qc') + '\n'
        'PATH_LOG=' + os.path.join('<path-output>', 'log') + '\n'
        'Which are respectively output paths for the processed data, results, quality control (QC) '
        'and logs')
    parser.add_argument(
        '-batch-log',
        default='sct_run_batch_log.txt',
        help='A log file for all terminal output produced by this script (not '
        'necessarily including the individual job outputs. File will be relative '
        'to "<path-output>/log".')
    parser.add_argument(
        '-include',
        help=
        'Optional regex used to filter the list of subject directories. Only process '
        'a subject if they match the regex. Inclusions are processed before exclusions. '
        'Cannot be used with `include-list`.')
    parser.add_argument(
        '-include-list',
        help=
        'Optional space separated list of subjects to include. Only process '
        'a subject if they are on this list. Inclusions are processed before exclusions. '
        'Cannot be used with `include`.',
        nargs='+')
    parser.add_argument(
        '-exclude',
        help=
        'Optional regex used to filter the list of subject directories. Only process '
        'a subject if they do not match the regex. Exclusions are processed '
        'after inclusions. Cannot be used with `exclude-list`')
    parser.add_argument(
        '-exclude-list',
        help=
        'Optional space separated list of subjects to exclude. Only process '
        'a subject if they are not on this list. Inclusions are processed before exclusions. '
        'Cannot be used with either `exclude`.',
        nargs='+')
    parser.add_argument(
        '-path-segmanual',
        default='.',
        help='Setting for environment variable: PATH_SEGMANUAL\n'
        'A path containing manual segmentations to be used by the script program.'
    )
    parser.add_argument(
        '-script-args',
        default='',
        help=
        'A quoted string with extra flags and arguments to pass to the script. '
        'For example \'sct_run_batch -path-data data/ -script-args "-foo bar -baz /qux" process_data.sh \''
    )
    parser.add_argument(
        '-email-to',
        help=
        'Optional email address where sct_run_batch can send an alert on completion of the '
        'batch processing.')
    parser.add_argument(
        '-email-from',
        help=
        'Optional alternative email to use to send the email. Defaults to the same address as '
        '`-email-to`')
    parser.add_argument(
        '-email-host',
        default='smtp.gmail.com:587',
        help=
        'Optional smtp server and port to use to send the email. Defaults to gmail\'s server. Note'
        ' that gmail server requires "Less secure apps access" to be turned on, which can be done '
        ' at https://myaccount.google.com/security')
    parser.add_argument(
        '-continue-on-error',
        type=int,
        default=1,
        choices=(0, 1),
        help='Whether the batch processing should continue if a subject fails.'
    )
    parser.add_argument('-script',
                        help='Shell script used to process the data.')
    parser.add_argument(
        '-zip',
        action='store_true',
        help='Create zip archive of output folders log/, qc/ and results/.')
    parser.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help=
        "Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )
    parser.add_argument('-h',
                        "--help",
                        action="help",
                        help="show this help message and exit")

    return parser
Exemple #22
0
def get_parser():
    parser = SCTArgumentParser(
        description=
        'Perform mathematical operations on images. Some inputs can be either a number or a 4d image or '
        'several 3d images separated with ","')

    mandatory = parser.add_argument_group("MANDATORY ARGUMENTS")
    mandatory.add_argument("-i",
                           metavar=Metavar.file,
                           help="Input file. Example: data.nii.gz",
                           required=True)
    mandatory.add_argument("-o",
                           metavar=Metavar.file,
                           help='Output file. Example: data_mean.nii.gz',
                           required=True)

    optional = parser.add_argument_group("OPTIONAL ARGUMENTS")
    optional.add_argument("-h",
                          "--help",
                          action="help",
                          help="Show this help message and exit")

    basic = parser.add_argument_group('BASIC OPERATIONS')
    basic.add_argument(
        "-add",
        metavar='',
        nargs="+",
        help=
        'Add following input. Can be a number or multiple images (separated with space).',
        required=False)
    basic.add_argument(
        "-sub",
        metavar='',
        nargs="+",
        help='Subtract following input. Can be a number or an image.',
        required=False)
    basic.add_argument(
        "-mul",
        metavar='',
        nargs="+",
        help=
        'Multiply by following input. Can be a number or multiple images (separated with space).',
        required=False)
    basic.add_argument(
        "-div",
        metavar='',
        nargs="+",
        help='Divide by following input. Can be a number or an image.',
        required=False)
    basic.add_argument('-mean',
                       help='Average data across dimension.',
                       required=False,
                       choices=('x', 'y', 'z', 't'))
    basic.add_argument('-rms',
                       help='Compute root-mean-squared across dimension.',
                       required=False,
                       choices=('x', 'y', 'z', 't'))
    basic.add_argument('-std',
                       help='Compute STD across dimension.',
                       required=False,
                       choices=('x', 'y', 'z', 't'))
    basic.add_argument(
        "-bin",
        type=float,
        metavar=Metavar.float,
        help='Binarize image using specified threshold. Example: 0.5',
        required=False)

    thresholding = parser.add_argument_group("THRESHOLDING METHODS")
    thresholding.add_argument(
        '-otsu',
        type=int,
        metavar=Metavar.int,
        help=
        'Threshold image using Otsu algorithm (from skimage). Specify the number of bins (e.g. 16, 64, 128)',
        required=False)
    thresholding.add_argument(
        "-adap",
        metavar=Metavar.list,
        type=list_type(',', int),
        help=
        "R|Threshold image using Adaptive algorithm (from skimage). Provide 2 values separated by ',' that "
        "correspond to the parameters below. For example, '-adap 7,0' corresponds to a block size of 7 and an "
        "offset of 0.\n"
        "  - Block size: Odd size of pixel neighborhood which is used to calculate the threshold value. \n"
        "  - Offset: Constant subtracted from weighted mean of neighborhood to calculate the local threshold "
        "value. Suggested offset is 0.",
        required=False)
    thresholding.add_argument(
        "-otsu-median",
        metavar=Metavar.list,
        type=list_type(',', int),
        help=
        "R|Threshold image using Median Otsu algorithm (from dipy). Provide 2 values separated by ',' that "
        "correspond to the parameters below. For example, '-otsu-median 3,5' corresponds to a filter size of 3 "
        "repeated over 5 iterations.\n"
        "  - Size: Radius (in voxels) of the applied median filter.\n"
        "  - Iterations: Number of passes of the median filter.",
        required=False)
    thresholding.add_argument(
        '-percent',
        type=int,
        help="Threshold image using percentile of its histogram.",
        metavar=Metavar.int,
        required=False)
    thresholding.add_argument(
        "-thr",
        type=float,
        help='Use following number to threshold image (zero below number).',
        metavar=Metavar.float,
        required=False)

    mathematical = parser.add_argument_group("MATHEMATICAL MORPHOLOGY")
    mathematical.add_argument(
        '-dilate',
        type=int,
        metavar=Metavar.int,
        help=
        "Dilate binary or greyscale image with specified size. If shape={'square', 'cube'}: size corresponds to the length of "
        "an edge (size=1 has no effect). If shape={'disk', 'ball'}: size corresponds to the radius, not including "
        "the center element (size=0 has no effect).",
        required=False)
    mathematical.add_argument(
        '-erode',
        type=int,
        metavar=Metavar.int,
        help=
        "Erode binary or greyscale image with specified size. If shape={'square', 'cube'}: size corresponds to the length of "
        "an edge (size=1 has no effect). If shape={'disk', 'ball'}: size corresponds to the radius, not including "
        "the center element (size=0 has no effect).",
        required=False)
    mathematical.add_argument(
        '-shape',
        help=
        "R|Shape of the structuring element for the mathematical morphology operation. Default: ball.\n"
        "If a 2D shape {'disk', 'square'} is selected, -dim must be specified.",
        required=False,
        choices=('square', 'cube', 'disk', 'ball'),
        default='ball')
    mathematical.add_argument(
        '-dim',
        type=int,
        help=
        "Dimension of the array which 2D structural element will be orthogonal to. For example, if you wish to "
        "apply a 2D disk kernel in the X-Y plane, leaving Z unaffected, parameters will be: shape=disk, dim=2.",
        required=False,
        choices=(0, 1, 2))

    filtering = parser.add_argument_group("FILTERING METHODS")
    filtering.add_argument(
        "-smooth",
        metavar=Metavar.list,
        type=list_type(',', float),
        help=
        'Gaussian smoothing filtering. Supply values for standard deviations in mm. If a single value is provided, '
        'it will be applied to each axis of the image. If multiple values are provided, there must be one value '
        'per image axis. (Examples: "-smooth 2.0,3.0,2.0" (3D image), "-smooth 2.0" (any-D image)).',
        required=False)
    filtering.add_argument(
        '-laplacian',
        metavar=Metavar.list,
        type=list_type(',', float),
        help=
        'Laplacian filtering. Supply values for standard deviations in mm. If a single value is provided, it will '
        'be applied to each axis of the image. If multiple values are provided, there must be one value per '
        'image axis. (Examples: "-laplacian 2.0,3.0,2.0" (3D image), "-laplacian 2.0" (any-D image)).',
        required=False)
    filtering.add_argument(
        '-denoise',
        help=
        'R|Non-local means adaptative denoising from P. Coupe et al. as implemented in dipy. Separate with ". Example: p=1,b=3\n'
        ' p: (patch radius) similar patches in the non-local means are searched for locally, inside a cube of side 2*p+1 centered at each voxel of interest. Default: p=1\n'
        ' b: (block radius) the size of the block to be used (2*b+1) in the blockwise non-local means implementation. Default: b=5 '
        '    Note, block radius must be smaller than the smaller image dimension: default value is lowered for small images)\n'
        'To use default parameters, write -denoise 1',
        required=False)

    similarity = parser.add_argument_group("SIMILARITY METRIC")
    similarity.add_argument(
        '-mi',
        metavar=Metavar.file,
        help=
        'Compute the mutual information (MI) between both input files (-i and -mi) as in: '
        'http://scikit-learn.org/stable/modules/generated/sklearn.metrics.mutual_info_score.html',
        required=False)
    similarity.add_argument(
        '-minorm',
        metavar=Metavar.file,
        help=
        'Compute the normalized mutual information (MI) between both input files (-i and -mi) as in: '
        'http://scikit-learn.org/stable/modules/generated/sklearn.metrics.normalized_mutual_info_score.html',
        required=False)
    similarity.add_argument(
        '-corr',
        metavar=Metavar.file,
        help=
        'Compute the cross correlation (CC) between both input files (-i and -cc).',
        required=False)

    misc = parser.add_argument_group("MISC")
    misc.add_argument('-symmetrize',
                      type=int,
                      help='Symmetrize data along the specified dimension.',
                      required=False,
                      choices=(0, 1, 2))
    misc.add_argument('-type',
                      required=False,
                      help='Output type.',
                      choices=('uint8', 'int16', 'int32', 'float32',
                               'complex64', 'float64', 'int8', 'uint16',
                               'uint32', 'int64', 'uint64'))
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help=
        "Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )

    return parser
Exemple #23
0
def get_parser():
    # initialize default parameters
    param_default = Param()

    # Initialize the parser
    parser = SCTArgumentParser(
        description="Smooth the spinal cord along its centerline. Steps are:\n"
        "  1) Spinal cord is straightened (using centerline),\n"
        "  2) a Gaussian kernel is applied in the superior-inferior direction,\n"
        "  3) then cord is de-straightened as originally.\n")

    mandatory = parser.add_argument_group("\nMANDATORY ARGUMENTS")
    mandatory.add_argument('-i',
                           metavar=Metavar.file,
                           required=True,
                           help="Image to smooth. Example: data.nii.gz")
    mandatory.add_argument(
        '-s',
        metavar=Metavar.file,
        required=True,
        help=
        "Spinal cord centerline or segmentation. Example: data_centerline.nii.gz"
    )

    optional = parser.add_argument_group("\nOPTIONAL ARGUMENTS")
    optional.add_argument("-h",
                          "--help",
                          action="help",
                          help="Show this help message and exit.")
    optional.add_argument(
        '-smooth',
        metavar=Metavar.list,
        type=list_type(',', float),
        default=[0, 0, 3],
        help=
        "Sigma (standard deviation) of the smoothing Gaussian kernel (in mm). For isotropic smoothing you only "
        "need to specify a value (e.g. 2). For anisotropic smoothing specify a value for each axis, separated "
        "with a comma. The order should follow axes Right-Left, Antero-Posterior, Superior-Inferior "
        "(e.g.: 1,1,3). For no smoothing, set value to 0.")
    optional.add_argument(
        '-algo-fitting',
        metavar=Metavar.str,
        choices=['bspline', 'polyfit'],
        default=param_default.algo_fitting,
        help=
        f"Algorithm for curve fitting. For more information, see sct_straighten_spinalcord."
    )
    optional.add_argument("-o",
                          metavar=Metavar.file,
                          help='Output filename. Example: smooth_sc.nii '),
    optional.add_argument(
        '-r',
        choices=[0, 1],
        default=1,
        help="Whether to remove temporary files. 0 = no, 1 = yes")
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help=
        "Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )

    return parser
Exemple #24
0
def get_parser():
    # initialize default param
    param_default = Param()
    parser = SCTArgumentParser(
        description=(
            "This function takes an anatomical image and its cord segmentation (binary file), and outputs the "
            "cord segmentation labeled with vertebral level. The algorithm requires an initialization (first disc) and "
            "then performs a disc search in the superior, then inferior direction, using template disc matching based "
            "on mutual information score. The automatic method uses the module implemented in "
            "'spinalcordtoolbox/vertebrae/detect_c2c3.py' to detect the C2-C3 disc.\n"
            "Tips: To run the function with init txt file that includes flags -initz/-initcenter:\n"
            "  sct_label_vertebrae -i t2.nii.gz -s t2_seg-manual.nii.gz  '$(< init_label_vertebrae.txt)'"
        )
    )

    mandatory = parser.add_argument_group("\nMANDATORY ARGUMENTS")
    mandatory.add_argument(
        '-i',
        metavar=Metavar.file,
        required=True,
        help="Input image. Example: t2.nii.gz"
    )
    mandatory.add_argument(
        '-s',
        metavar=Metavar.file,
        required=True,
        help="Segmentation of the spinal cord. Example: t2_seg.nii.gz"
    )
    mandatory.add_argument(
        '-c',
        choices=['t1', 't2'],
        required=True,
        help="Type of image contrast. 't2': cord dark / CSF bright. 't1': cord bright / CSF dark"
    )

    optional = parser.add_argument_group("\nOPTIONAL ARGUMENTS")
    optional.add_argument(
        "-h",
        "--help",
        action="help",
        help="Show this help message and exit."
    )
    optional.add_argument(
        '-t',
        metavar=Metavar.folder,
        default=os.path.join(__data_dir__, "PAM50"),
        help="Path to template."
    )
    optional.add_argument(
        '-initz',
        metavar=Metavar.list,
        type=list_type(',', int),
        help="R|Initialize using slice number and disc value. Example: 68,4 (slice 68 corresponds to disc C3/C4). "
             "Example: 125,3\n"
             "WARNING: Slice number should correspond to superior-inferior direction (e.g. Z in RPI orientation, but "
             "Y in LIP orientation)."
    )
    optional.add_argument(
        '-initcenter',
        metavar=Metavar.int,
        type=int,
        help="Initialize using disc value centered in the rostro-caudal direction. If the spine is curved, then "
             "consider the disc that projects onto the cord at the center of the z-FOV."
    )
    optional.add_argument(
        '-initfile',
        metavar=Metavar.file,
        help="Initialize labeling by providing a text file which includes either -initz or -initcenter flag."
    )
    optional.add_argument(
        '-initlabel',
        metavar=Metavar.file,
        help="Initialize vertebral labeling by providing a nifti file that has a single disc label. An example of "
             "such file is a single voxel with value '3', which would be located at the posterior tip of C2-C3 disc. "
             "Such label file can be created using: sct_label_utils -i IMAGE_REF -create-viewer 3 ; or by using the "
             "Python module 'detect_c2c3' implemented in 'spinalcordtoolbox/vertebrae/detect_c2c3.py'."
    )
    optional.add_argument(
        '-discfile',
        metavar=Metavar.file,
        help="File with disc labels, which will be used to transform the input segmentation into a vertebral level "
             "file. In that case, there will be no disc detection. The convention for disc labels is the following: "
             "value=3 -> disc C2/C3, value=4 -> disc C3/C4, etc."
    )
    optional.add_argument(
        '-ofolder',
        metavar=Metavar.file,
        action=ActionCreateFolder,
        default='',
        help="Output folder."
    )
    optional.add_argument(
        '-laplacian',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1],
        default=0,
        help="Apply Laplacian filtering. More accurate but could mistake disc depending on anatomy."
    )
    optional.add_argument(
        '-clean-labels',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1],
        default=0,
        help=" Clean output labeled segmentation to resemble original segmentation."
    )
    optional.add_argument(
        '-scale-dist',
        metavar=Metavar.float,
        type=float,
        default=1.,
        help="Scaling factor to adjust the average distance between two adjacent intervertebral discs. For example, "
             "if you are dealing with images from pediatric population, the distance should be reduced, so you can "
             "try a scaling factor of about 0.7."
    )
    optional.add_argument(
        '-param',
        metavar=Metavar.list,
        type=list_type(',', str),
        help=f"R|Advanced parameters. Assign value with \"=\"; Separate arguments with \",\"\n"
             f"  - shift_AP [mm]: AP shift of centerline for disc search. Default={param_default.shift_AP}.\n"
             f"  - size_AP [mm]: AP window size for disc search. Default={param_default.size_AP}.\n"
             f"  - size_RL [mm]: RL window size for disc search. Default={param_default.size_RL}.\n"
             f"  - size_IS [mm]: IS window size for disc search. Default={param_default.size_IS}.\n"
             f"  - gaussian_std [mm]: STD of the Gaussian function, centered at the most rostral point of the "
             f"image, and used to weight C2-C3 disk location finding towards the rostral portion of the FOV. Values "
             f"to set between 0.1 (strong weighting) and 999 (no weighting). "
             f"Default={param_default.gaussian_std}.\n"
    )
    optional.add_argument(
        '-r',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1],
        default=1,
        help="Remove temporary files."
    )
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help="Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )
    optional.add_argument(
        '-qc',
        metavar=Metavar.folder,
        action=ActionCreateFolder,
        default=param_default.path_qc,
        help="The path where the quality control generated content will be saved."
    )
    optional.add_argument(
        '-qc-dataset',
        metavar=Metavar.str,
        help="If provided, this string will be mentioned in the QC report as the dataset the process was run on."
    )
    optional.add_argument(
        '-qc-subject',
        metavar=Metavar.str,
        help="If provided, this string will be mentioned in the QC report as the subject the process was run on."
    )

    return parser
def get_parser():
    parser = SCTArgumentParser(description=(
        "This function extracts the spinal cord centerline. Three methods are available: 'optic' (automatic), "
        "'viewer' (manual), and 'fitseg' (applied on segmented image). These functions output (i) a NIFTI file "
        "with labels corresponding to the discrete centerline, and (ii) a csv file containing the float (more "
        "precise) coordinates of the centerline in the RPI orientation. \n"
        "\n"
        "Reference: C Gros, B De Leener, et al. Automatic spinal cord localization, robust to MRI contrast using "
        "global curve optimization (2017). doi.org/10.1016/j.media.2017.12.001"
    ))

    mandatory = parser.add_argument_group("\nMANDATORY ARGUMENTS")
    mandatory.add_argument('-i',
                           metavar=Metavar.file,
                           required=True,
                           help="Input image. Example: t1.nii.gz")

    optional = parser.add_argument_group("\nOPTIONAL ARGUMENTS")
    optional.add_argument("-h",
                          "--help",
                          action="help",
                          help="Show this help message and exit.")
    optional.add_argument(
        "-c",
        choices=['t1', 't2', 't2s', 'dwi'],
        help="Type of image contrast. Only with method=optic.")
    optional.add_argument(
        "-method",
        choices=['optic', 'viewer', 'fitseg'],
        default='optic',
        help="R|Method used for extracting the centerline.\n"
        "  - optic: automatic spinal cord detection method\n"
        "  - viewer: manual selection a few points followed by interpolation\n"
        "  - fitseg: fit a regularized centerline on an already-existing cord segmentation. It will "
        "interpolate if slices are missing and extrapolate beyond the segmentation boundaries (i.e., every "
        "axial slice will exhibit a centerline pixel).")
    optional.add_argument(
        "-centerline-algo",
        choices=['polyfit', 'bspline', 'linear', 'nurbs'],
        default='bspline',
        help=
        "Algorithm for centerline fitting. Only relevant with -method fitseg")
    optional.add_argument(
        "-centerline-smooth",
        metavar=Metavar.int,
        type=int,
        default=30,
        help=
        "Degree of smoothing for centerline fitting. Only for -centerline-algo {bspline, linear}."
    )
    optional.add_argument(
        "-o",
        metavar=Metavar.file,
        help=
        "File name (without extension) for the centerline output files. By default, output file will be the "
        "input with suffix '_centerline'. Example: 'centerline_optic'")
    optional.add_argument(
        "-gap",
        metavar=Metavar.float,
        type=float,
        default=20.0,
        help=
        "Gap in mm between manually selected points. Only with method=viewer.")
    optional.add_argument(
        "-igt",
        metavar=Metavar.file,
        help=
        "File name of ground-truth centerline or segmentation (binary nifti).")
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help=
        "Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )
    optional.add_argument(
        "-qc",
        metavar=Metavar.folder,
        action=ActionCreateFolder,
        help=
        "The path where the quality control generated content will be saved.")
    optional.add_argument(
        "-qc-dataset",
        metavar=Metavar.str,
        help=
        "If provided, this string will be mentioned in the QC report as the dataset the process was run on."
    )
    optional.add_argument(
        "-qc-subject",
        metavar=Metavar.str,
        help=
        "If provided, this string will be mentioned in the QC report as the subject the process was run on."
    )
    return parser
def get_parser():
    parser = SCTArgumentParser(
        description=
        'Apply transformations. This function is a wrapper for antsApplyTransforms (ANTs).'
    )

    mandatoryArguments = parser.add_argument_group("\nMANDATORY ARGUMENTS")
    mandatoryArguments.add_argument(
        "-i",
        required=True,
        help='Input image. Example: t2.nii.gz',
        metavar=Metavar.file,
    )
    mandatoryArguments.add_argument(
        "-d",
        required=True,
        help='Destination image. Example: out.nii.gz',
        metavar=Metavar.file,
    )
    mandatoryArguments.add_argument(
        "-w",
        nargs='+',
        required=True,
        help=
        'Transformation(s), which can be warping fields (nifti image) or affine transformation matrix (text '
        'file). Separate with space. Example: warp1.nii.gz warp2.nii.gz',
        metavar=Metavar.file,
    )

    optional = parser.add_argument_group("\nOPTIONAL ARGUMENTS")
    optional.add_argument(
        "-winv",
        help=
        'Affine transformation(s) listed in flag -w which should be inverted before being used. Note that this '
        'only concerns affine transformation (not warping fields). If you would like to use an inverse warping '
        'field, then directly input the inverse warping field in flag -w.',
        nargs='+',
        metavar=Metavar.file,
        default=[])
    optional.add_argument("-h",
                          "--help",
                          action="help",
                          help="Show this help message and exit")
    optional.add_argument(
        "-crop",
        help=
        "Crop Reference. 0: no reference, 1: sets background to 0, 2: use normal background.",
        required=False,
        type=int,
        default=0,
        choices=(0, 1, 2))
    optional.add_argument("-o",
                          help='Registered source. Example: dest.nii.gz',
                          required=False,
                          metavar=Metavar.file,
                          default='')
    optional.add_argument(
        "-x",
        help=
        """ Interpolation method. The 'label' method is to be used if you would like to apply a transformation
        on a file that has single-voxel labels (classical interpolation methods won't work, as resampled labels might
        disappear or their values be altered). The function will dilate each label, apply the transformation using
        nearest neighbour interpolation, and then take the center-of-mass of each "blob" and output a single voxel per
        blob.""",
        required=False,
        default='spline',
        choices=('nn', 'linear', 'spline', 'label'))
    optional.add_argument("-r",
                          help="""Remove temporary files.""",
                          required=False,
                          type=int,
                          default=1,
                          choices=(0, 1))
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help=
        "Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )

    return parser
def get_parser():
    # initialize parameters
    # TODO: create a class ParamFmriMoco which inheritates from ParamMoco
    param_default = ParamMoco(group_size=1, metric='MeanSquares', smooth='0')

    # parser initialisation
    parser = SCTArgumentParser(
        description=
        "Motion correction of fMRI data. Some robust features include:\n"
        "  - group-wise (-g)\n"
        "  - slice-wise regularized along z using polynomial function (-p)\n"
        "    (For more info about the method, type: isct_antsSliceRegularizedRegistration)\n"
        "  - masking (-m)\n"
        "  - iterative averaging of target volume\n"
        "\n"
        "The outputs of the motion correction process are:\n"
        "  - the motion-corrected fMRI volumes\n"
        "  - the time average of the corrected fMRI volumes\n"
        "  - a time-series with 1 voxel in the XY plane, for the X and Y motion direction (two separate "
        "files), as required for FSL analysis.\n"
        "  - a TSV file with the slice-wise average of the motion correction for XY (one file), that "
        "can be used for Quality Control.\n")

    mandatory = parser.add_argument_group("\nMANDATORY ARGUMENTS")
    mandatory.add_argument('-i',
                           metavar=Metavar.file,
                           required=True,
                           help="Input data (4D). Example: fmri.nii.gz")
    optional = parser.add_argument_group("\nOPTIONAL ARGUMENTS")
    optional.add_argument("-h",
                          "--help",
                          action="help",
                          help="Show this help message and exit.")
    optional.add_argument(
        '-g',
        metavar=Metavar.int,
        type=int,
        help="Group nvols successive fMRI volumes for more robustness.")
    optional.add_argument(
        '-m',
        metavar=Metavar.file,
        help=
        "Binary mask to limit voxels considered by the registration metric.")
    optional.add_argument(
        '-param',
        metavar=Metavar.list,
        type=list_type(',', str),
        help=
        f"Advanced parameters. Assign value with \"=\"; Separate arguments with \",\".\n"
        f"  - poly [int]: Degree of polynomial function used for regularization along Z. For no regularization "
        f"set to 0. Default={param_default.poly}.\n"
        f"  - smooth [mm]: Smoothing kernel. Default={param_default.smooth}.\n"
        f"  - iter [int]: Number of iterations. Default={param_default.iter}.\n"
        f"  - metric {{MI, MeanSquares, CC}}: Metric used for registration. Default={param_default.metric}.\n"
        f"  - gradStep [float]: Searching step used by registration algorithm. The higher the more deformation "
        f"allowed. Default={param_default.gradStep}.\n"
        f"  - sampling [None or 0-1]: Sampling rate used for registration metric. "
        f"Default={param_default.sampling}.\n"
        f"  - numTarget [int]: Target volume or group (starting with 0). Default={param_default.num_target}.\n"
        f"  - iterAvg [int]: Iterative averaging: Target volume is a weighted average of the "
        f"previously-registered volumes. Default={param_default.iterAvg}.\n")
    optional.add_argument('-ofolder',
                          metavar=Metavar.folder,
                          action=ActionCreateFolder,
                          default='.',
                          help="Output path.")
    optional.add_argument('-x',
                          choices=['nn', 'linear', 'spline'],
                          default='linear',
                          help="Final interpolation.")
    optional.add_argument('-r',
                          metavar=Metavar.int,
                          type=int,
                          choices=[0, 1],
                          default=1,
                          help="Remove temporary files. O = no, 1 = yes")
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help=
        "Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )
    optional.add_argument(
        '-qc',
        metavar=Metavar.folder,
        action=ActionCreateFolder,
        help=
        "The path where the quality control generated content will be saved. (Note: "
        "Both '-qc' and '-qc-seg' are required in order to generate a QC report.)"
    )
    optional.add_argument(
        '-qc-seg',
        metavar=Metavar.file,
        help=
        "Segmentation of spinal cord to improve cropping in qc report. (Note: "
        "Both '-qc' and '-qc-seg' are required in order to generate a QC report.)"
    )
    optional.add_argument(
        '-qc-fps',
        metavar=Metavar.float,
        type=float,
        default=3,
        help=
        "This float number is the number of frames per second for the output gif images."
    )
    optional.add_argument(
        '-qc-dataset',
        metavar=Metavar.str,
        help=
        "If provided, this string will be mentioned in the QC report as the dataset the process was run on."
    )
    optional.add_argument(
        '-qc-subject',
        metavar=Metavar.str,
        help=
        "If provided, this string will be mentioned in the QC report as the subject the process was run on."
    )

    return parser
def get_parser():
    parser = SCTArgumentParser(
        description=
        "This program takes as input an anatomic image and the spinal cord centerline (or "
        "segmentation), and returns the an image of a straightened spinal cord. Reference: "
        "De Leener B, Mangeat G, Dupont S, Martin AR, Callot V, Stikov N, Fehlings MG, "
        "Cohen-Adad J. Topologically-preserving straightening of spinal cord MRI. J Magn "
        "Reson Imaging. 2017 Oct;46(4):1209-1219")
    mandatory = parser.add_argument_group("MANDATORY ARGUMENTS")
    mandatory.add_argument(
        "-i",
        metavar=Metavar.file,
        help='Input image with curved spinal cord. Example: "t2.nii.gz"',
        required=True)
    mandatory.add_argument(
        "-s",
        metavar=Metavar.file,
        help=
        'Spinal cord centerline (or segmentation) of the input image. To obtain the centerline, you can use '
        'sct_get_centerline. To obtain the segmentation you can use sct_propseg or sct_deepseg_sc. '
        'Example: centerline.nii.gz',
        required=True)
    optional = parser.add_argument_group("OPTIONAL ARGUMENTS")
    optional.add_argument("-h",
                          "--help",
                          action="help",
                          help="Show this help message and exit")
    optional.add_argument(
        "-dest",
        metavar=Metavar.file,
        help=
        "Spinal cord centerline (or segmentation) of a destination image (which could be "
        "straight or curved). An algorithm scales the length of the input centerline to match that of the "
        "destination centerline. If using -ldisc-input and -ldisc-dest with this parameter, "
        "instead of linear scaling, the source centerline will be non-linearly matched so "
        "that the inter-vertebral discs of the input image will match that of the "
        "destination image. This feature is particularly useful for registering to a "
        "template while accounting for disc alignment.",
        required=False)
    optional.add_argument(
        "-ldisc-input",
        metavar=Metavar.file,
        help=
        "Labels located at the posterior edge of the intervertebral discs, for the input  "
        "image (-i). All disc covering the region of interest should be provided. Exmaple: if "
        "you are interested in levels C2 to C7, then you should provide disc labels 2,3,4,5,"
        "6,7). More details about label creation at "
        "http://sourceforge.net/p/spinalcordtoolbox/wiki/create_labels/. "  # TODO (Julien) update this link
        "This option must be used with the -ldisc-dest parameter.",
        required=False)
    optional.add_argument(
        "-ldisc-dest",
        metavar=Metavar.file,
        help=
        "Labels located at the posterior edge of the intervertebral discs, for the destination file (-dest). "
        "The same comments as in -ldisc-input apply. This option must be used with the -ldisc-input parameter.",
        required=False)
    optional.add_argument(
        "-disable-straight2curved",
        action='store_true',
        help=
        "Disable straight to curved transformation computation, in case you do not need the "
        "output warping field straight-->curve (faster).",
        required=False)
    optional.add_argument(
        "-disable-curved2straight",
        action='store_true',
        help=
        "Disable curved to straight transformation computation, in case you do not need the "
        "output warping field curve-->straight (faster).",
        required=False)
    optional.add_argument(
        "-speed-factor",
        metavar=Metavar.float,
        type=float,
        help=
        'Acceleration factor for the calculation of the straightening warping field.'
        ' This speed factor enables an intermediate resampling to a lower resolution, which '
        'decreases the computational time at the cost of lower accuracy.'
        ' A speed factor of 2 means that the input image will be downsampled by a factor 2 '
        'before calculating the straightening warping field. For example, a 1x1x1 mm^3 image '
        'will be downsampled to 2x2x2 mm3, providing a speed factor of approximately 8.'
        ' Note that accelerating the straightening process reduces the precision of the '
        'algorithm, and induces undesirable edges effects. Default=1 (no downsampling).',
        required=False,
        default=1)
    optional.add_argument(
        "-xy-size",
        metavar=Metavar.float,
        type=float,
        help=
        'Size of the output FOV in the RL/AP plane, in mm. The resolution of the destination '
        'image is the same as that of the source image (-i). Default: 35.',
        required=False,
        default=35.0)
    optional.add_argument(
        "-o",
        metavar=Metavar.file,
        help=
        'Straightened file. By default, the suffix "_straight" will be added to the input file name.',
        required=False,
        default='')
    optional.add_argument("-ofolder",
                          metavar=Metavar.folder,
                          help="Output folder (all outputs will go there).",
                          action=ActionCreateFolder,
                          required=False,
                          default='./')
    optional.add_argument(
        '-centerline-algo',
        help='Algorithm for centerline fitting. Default: nurbs.',
        choices=('bspline', 'linear', 'nurbs'),
        default='nurbs')
    optional.add_argument(
        '-centerline-smooth',
        metavar=Metavar.int,
        type=int,
        help=
        'Degree of smoothing for centerline fitting. Only use with -centerline-algo {bspline, linear}. Default: 10',
        default=10)

    optional.add_argument(
        "-param",
        metavar=Metavar.list,
        help=
        "R|Parameters for spinal cord straightening. Separate arguments with \",\".\n"
        "  - precision: Float [1, inf) Precision factor of straightening, related to the number of slices. Increasing this parameter increases the precision along with increased computational time. Not taken into account with Hanning fitting method. Default=2\n"
        "  - threshold_distance: Float [0, inf) Threshold at which voxels are not considered into displacement. Increase this threshold if the image is blackout around the spinal cord too much. Default=10\n"
        "  - accuracy_results: {0, 1} Disable/Enable computation of accuracy results after straightening. Default=0\n"
        "  - template_orientation: {0, 1} Disable/Enable orientation of the straight image to be the same as the template. Default=0",
        required=False)

    optional.add_argument("-x",
                          help="Final interpolation. Default: spline.",
                          choices=("nn", "linear", "spline"),
                          default="spline")
    optional.add_argument(
        '-qc',
        metavar=Metavar.str,
        help=
        'The path where the quality control generated content will be saved',
        default=None)
    optional.add_argument(
        '-qc-dataset',
        metavar=Metavar.str,
        help=
        'If provided, this string will be mentioned in the QC report as the dataset the '
        'process was run on',
        default=None)
    optional.add_argument(
        '-qc-subject',
        metavar=Metavar.str,
        help=
        'If provided, this string will be mentioned in the QC report as the subject the '
        'process was run on',
        default=None)
    optional.add_argument("-r",
                          type=int,
                          help="Remove temporary files.",
                          required=False,
                          choices=(0, 1),
                          default=1)
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help=
        "Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )

    return parser
def get_parser():
    parser = SCTArgumentParser(
        description=
        'MS lesion Segmentation using convolutional networks. Reference: Gros C et al. Automatic'
        'segmentation of the spinal cord and intramedullary multiple sclerosis lesions with convolutional'
        'neural networks. Neuroimage. 2018 Oct 6;184:901-915.')

    mandatory = parser.add_argument_group("\nMANDATORY ARGUMENTS")
    mandatory.add_argument(
        "-i",
        required=True,
        help='Input image. Example: t1.nii.gz',
        metavar=Metavar.file,
    )
    mandatory.add_argument(
        "-c",
        required=True,
        help='Type of image contrast.\n'
        ' t2: T2w scan with isotropic or anisotropic resolution.\n'
        ' t2_ax: T2w scan with axial orientation and thick slices.\n'
        ' t2s: T2*w scan with axial orientation and thick slices.',
        choices=('t2', 't2_ax', 't2s'),
    )

    optional = parser.add_argument_group("\nOPTIONAL ARGUMENTS")
    optional.add_argument(
        "-h",
        "--help",
        action="help",
        help="Show this help message and exit",
    )
    optional.add_argument(
        "-centerline",
        help="Method used for extracting the centerline:\n"
        " svm: Automatic detection using Support Vector Machine algorithm.\n"
        " cnn: Automatic detection using Convolutional Neural Network.\n"
        " viewer: Semi-automatic detection using manual selection of a few points with an interactive viewer "
        "followed by regularization.\n"
        " file: Use an existing centerline (use with flag -file_centerline)",
        required=False,
        choices=('svm', 'cnn', 'viewer', 'file'),
        default="svm")
    optional.add_argument(
        "-file_centerline",
        help=
        'Input centerline file (to use with flag -centerline manual). Example: t2_centerline_manual.nii.gz',
        metavar=Metavar.str,
        required=False)
    optional.add_argument(
        "-brain",
        type=int,
        help=
        'Indicate if the input image contains brain sections (to speed up segmentation). This flag is only '
        'effective with "-centerline cnn".',
        required=False,
        choices=(0, 1),
        default=1)
    optional.add_argument("-ofolder",
                          help='Output folder. Example: My_Output_Folder',
                          required=False,
                          action=ActionCreateFolder,
                          metavar=Metavar.str,
                          default=os.getcwd())
    optional.add_argument("-r",
                          type=int,
                          help="Remove temporary files.",
                          required=False,
                          choices=(0, 1),
                          default=1)
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help=
        "Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )
    optional.add_argument('-igt',
                          metavar=Metavar.str,
                          help='File name of ground-truth segmentation.',
                          required=False)

    return parser
def get_parser():
    # Initialize the parser
    parser = SCTArgumentParser(
        description="This program co-registers two 3D volumes. The deformation is non-rigid and is constrained along "
                    "Z direction (i.e., axial plane). Hence, this function assumes that orientation of the destination "
                    "image is axial (RPI). If you need to register two volumes with large deformations and/or "
                    "different contrasts, it is recommended to input spinal cord segmentations (binary mask) in order "
                    "to achieve maximum robustness. The program outputs a warping field that can be used to register "
                    "other images to the destination image. To apply the warping field to another image, use "
                    "'sct_apply_transfo'\n"
                    "\n"
                    "Tips:\n"
                    " - For a registration step using segmentations, use the MeanSquares metric. Also, simple "
                    "algorithm will be very efficient, for example centermass as a 'preregistration'.\n"
                    " - For a registration step using images of different contrast, use the Mutual Information (MI) "
                    "metric.\n"
                    " - Combine the steps by increasing the complexity of the transformation performed in each step, "
                    "for example: -param step=1,type=seg,algo=slicereg,metric=MeanSquares:"
                    "step=2,type=seg,algo=affine,metric=MeanSquares,gradStep=0.2:"
                    "step=3,type=im,algo=syn,metric=MI,iter=5,shrink=2\n"
                    " - When image contrast is low, a good option is to perform registration only based on the image "
                    "segmentation, i.e. using type=seg\n"
                    " - Columnwise algorithm needs to be applied after a translation and rotation such as centermassrot "
                    "algorithm. For example: -param step=1,type=seg,algo=centermassrot,metric=MeanSquares:"
                    "step=2,type=seg,algo=columnwise,metric=MeanSquares"
    )

    mandatory = parser.add_argument_group("\nMANDATORY ARGUMENTS")
    mandatory.add_argument(
        '-i',
        metavar=Metavar.file,
        required=True,
        help="Image source. Example: src.nii.gz"
    )
    mandatory.add_argument(
        '-d',
        metavar=Metavar.file,
        required=True,
        help="Image destination. Example: dest.nii.gz"
    )

    optional = parser.add_argument_group("\nOPTIONAL ARGUMENTS")
    optional.add_argument(
        "-h",
        "--help",
        action="help",
        help="Show this help message and exit."
    )
    optional.add_argument(
        '-iseg',
        metavar=Metavar.file,
        help="Segmentation source. Example: src_seg.nii.gz"
    )
    optional.add_argument(
        '-dseg',
        metavar=Metavar.file,
        help="Segmentation destination. Example: dest_seg.nii.gz"
    )
    optional.add_argument(
        '-ilabel',
        metavar=Metavar.file,
        help="Labels source."
    )
    optional.add_argument(
        '-dlabel',
        metavar=Metavar.file,
        help="Labels destination."
    )
    optional.add_argument(
        '-initwarp',
        metavar=Metavar.file,
        help="Initial warping field to apply to the source image."
    )
    optional.add_argument(
        '-initwarpinv',
        metavar=Metavar.file,
        help="Initial inverse warping field to apply to the destination image (only use if you wish to generate the "
             "dest->src warping field)"
    )
    optional.add_argument(
        '-m',
        metavar=Metavar.file,
        help="Mask that can be created with sct_create_mask to improve accuracy over region of interest. This mask "
             "will be used on the destination image. Example: mask.nii.gz"
    )
    optional.add_argument(
        '-o',
        metavar=Metavar.file,
        help="Name of output file. Example: src_reg.nii.gz"
    )
    optional.add_argument(
        '-owarp',
        metavar=Metavar.file,
        help="Name of output forward warping field."
    )
    optional.add_argument(
        '-owarpinv',
        metavar=Metavar.file,
        help="Name of output inverse warping field."
    )
    optional.add_argument(
        '-param',
        metavar=Metavar.list,
        type=list_type(':', str),
        help=(f"Parameters for registration. Separate arguments with \",\". Separate steps with \":\".\n"
              f"Example: step=1,type=seg,algo=slicereg,metric=MeanSquares:step=2,type=im,algo=syn,metric=MI,iter=5,"
              f"shrink=2\n"
              f"  - step: <int> Step number (starts at 1, except for type=label).\n"
              f"  - type: {{im, seg, imseg, label}} type of data used for registration. Use type=label only at "
              f"step=0.\n"
              f"  - algo: The algorithm used to compute the transformation. Default={DEFAULT_PARAMREGMULTI.steps['1'].algo}\n"
              f"    * translation: translation in X-Y plane (2dof)\n"
              f"    * rigid: translation + rotation in X-Y plane (4dof)\n"
              f"    * affine: translation + rotation + scaling in X-Y plane (6dof)\n"
              f"    * syn: non-linear symmetric normalization\n"
              f"    * bsplinesyn: syn regularized with b-splines\n"
              f"    * slicereg: regularized translations (see: goo.gl/Sj3ZeU)\n"
              f"    * centermass: slicewise center of mass alignment (seg only).\n"
              f"    * centermassrot: slicewise center of mass and rotation alignment using method specified in "
              f"'rot_method'\n"
              f"    * columnwise: R-L scaling followed by A-P columnwise alignment (seg only).\n"
              f"  - slicewise: <int> Slice-by-slice 2d transformation. "
              f"Default={DEFAULT_PARAMREGMULTI.steps['1'].slicewise}.\n"
              f"  - metric: {{CC, MI, MeanSquares}}. Default={DEFAULT_PARAMREGMULTI.steps['1'].metric}.\n"
              f"    * CC: The cross correlation metric compares the images based on their intensities but with a small "
              f"normalization. It can be used with images with the same contrast (for ex. T2-w with T2-w). In this "
              f"case it is very efficient but the computation time can be very long.\n"
              f"    * MI: the mutual information metric compares the images based on their entropy, therefore the "
              f"images need to be big enough to have enough information. It works well for images with different "
              f"contrasts (for example T2-w with T1-w) but not on segmentations.\n"
              f"    * MeanSquares: The mean squares metric compares the images based on their intensities. It can be "
              f"used only with images that have exactly the same contrast (with the same intensity range) or with "
              f"segmentations.\n"
              f"  - iter: <int> Number of iterations. Default={DEFAULT_PARAMREGMULTI.steps['1'].iter}.\n"
              f"  - shrink: <int> Shrink factor. A shrink factor of 2 will down sample the images by a factor of 2 to "
              f"do the registration, and thus allow bigger deformations (and be faster to compute). It is usually "
              f"combined with a smoothing. (only for syn/bsplinesyn). Default={DEFAULT_PARAMREGMULTI.steps['1'].shrink}.\n"
              f"  - smooth: <int> Smooth factor (in mm). Note: if algo={{centermassrot,columnwise}} the smoothing "
              f"kernel is: SxSx0. Otherwise it is SxSxS. Default={DEFAULT_PARAMREGMULTI.steps['1'].smooth}.\n"
              f"  - laplacian: <int> Laplace filter using Gaussian second derivatives, applied before registration. "
              f"The input number correspond to the standard deviation of the Gaussian filter. "
              f"Default={DEFAULT_PARAMREGMULTI.steps['1'].laplacian}.\n"
              f"  - gradStep: <float> The gradient step used by the function opitmizer. A small gradient step can lead "
              f"to a more accurate registration but will take longer to compute, with the risk to not reach "
              f"convergence. A bigger gradient step will make the registration faster but the result can be far from "
              f"an optimum. Default={DEFAULT_PARAMREGMULTI.steps['1'].gradStep}.\n"
              f"  - deformation: ?x?x?: Restrict deformation (for ANTs algo). Replace ? by 0 (no deformation) or 1 "
              f"(deformation). Default={DEFAULT_PARAMREGMULTI.steps['1'].deformation}.\n"
              f"  - init: Initial translation alignment based on:\n"
              f"    * geometric: Geometric center of images\n"
              f"    * centermass: Center of mass of images\n"
              f"    * origin: Physical origin of images\n"
              f"  - poly: <int> Polynomial degree of regularization (only for algo=slicereg). "
              f"Default={DEFAULT_PARAMREGMULTI.steps['1'].poly}.\n"
              f"  - filter_size: <float> Filter size for regularization (only for algo=centermassrot). "
              f"Default={DEFAULT_PARAMREGMULTI.steps['1'].filter_size}.\n"
              f"  - smoothWarpXY: <int> Smooth XY warping field (only for algo=columnwize). "
              f"Default={DEFAULT_PARAMREGMULTI.steps['1'].smoothWarpXY}.\n"
              f"  - pca_eigenratio_th: <int> Min ratio between the two eigenvalues for PCA-based angular adjustment "
              f"(only for algo=centermassrot and rot_method=pca). "
              f"Default={DEFAULT_PARAMREGMULTI.steps['1'].pca_eigenratio_th}.\n"
              f"  - dof: <str> Degree of freedom for type=label. Separate with '_'. T stands for translation and R "
              f"stands for rotation, x, y, and z indicating the direction. For example, Tx_Ty_Tz_Rx_Ry_Rz would allow "
              f"translation on x, y and z axes and rotation on x, y and z axes. "
              f"Default={DEFAULT_PARAMREGMULTI.steps['0'].dof}.\n"
              f"  - rot_method {{pca, hog, pcahog}}: rotation method to be used with algo=centermassrot. If using hog "
              f"or pcahog, type should be set to imseg. Default={DEFAULT_PARAMREGMULTI.steps['1'].rot_method}\n"
              f"    * pca: approximate cord segmentation by an ellipse and finds it orientation using PCA's "
              f"eigenvectors\n"
              f"    * hog: finds the orientation using the symmetry of the image\n"
              f"    * pcahog: tries method pca and if it fails, uses method hog.\n")
    )
    optional.add_argument(
        '-identity',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1],
        default=0,
        help="Supplying this option will skip registration optimization (e.g. translations, rotations, deformations) "
             "and will only rely on the qform (from the NIfTI header) of the source and destination images. Use this "
             "option if you wish to put the source image into the space of the destination image (i.e. match "
             "dimension, resolution and orientation)."
    )
    optional.add_argument(
        '-z',
        metavar=Metavar.int,
        type=int,
        default=Param().padding,
        help="Size of z-padding to enable deformation at edges when using SyN."
    )
    optional.add_argument(
        '-x',
        choices=['nn', 'linear', 'spline'],
        default='linear',
        help="Final interpolation."
    )
    optional.add_argument(
        '-ofolder',
        metavar=Metavar.folder,
        action=ActionCreateFolder,
        help="Output folder. Example: reg_results"
    )
    optional.add_argument(
        '-qc',
        metavar=Metavar.folder,
        action=ActionCreateFolder,
        help="The path where the quality control generated content will be saved."
    )
    optional.add_argument(
        '-qc-dataset',
        metavar=Metavar.str,
        help="If provided, this string will be mentioned in the QC report as the dataset the process was run on."
    )
    optional.add_argument(
        '-qc-subject',
        metavar=Metavar.str,
        help="If provided, this string will be mentioned in the QC report as the subject the process was run on."
    )
    optional.add_argument(
        '-r',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1],
        default=1,
        help="Whether to remove temporary files. 0 = no, 1 = yes"
    )
    optional.add_argument(
        '-v',
        metavar=Metavar.int,
        type=int,
        choices=[0, 1, 2],
        default=1,
        # Values [0, 1, 2] map to logging levels [WARNING, INFO, DEBUG], but are also used as "if verbose == #" in API
        help="Verbosity. 0: Display only errors/warnings, 1: Errors/warnings + info messages, 2: Debug mode"
    )
    return parser