コード例 #1
0
def load_data(arg):
    if is_float(arg):
        data = float(arg)
    else:
        if not os.path.isfile(arg):
            raise ValueError('Input file {} does not exist.'.format(arg))
        data = np.asanyarray(nib.load(arg).dataobj)
        logging.info('Loaded {} of shape {} and data_type {}.'.format(
            arg, data.shape, data.dtype))

        if data.ndim > 3:
            logging.warning('{} has {} dimensions, be careful.'.format(
                arg, data.ndim))
        elif data.ndim < 3:
            raise ValueError('{} has {} dimensions, not valid.'.format(
                arg, data.ndim))

    return data
コード例 #2
0
def load_data(arg):
    if is_float(arg):
        data = float(arg)
    else:
        if not os.path.isfile(arg):
            logging.error('Input file %s does not exist', arg)
            raise ValueError
        data = nib.load(arg).get_data()
        logging.info('Loaded %s of shape %s and data_type %s',
                     arg, data.shape, data.dtype)

        if data.ndim > 3:
            logging.warning('%s has %s dimensions, be careful', arg, data.ndim)
        elif data.ndim < 3:
            logging.warning('%s has %s dimensions, not valid ', arg, data.ndim)
            raise ValueError

    return data
コード例 #3
0
def load_data(arg):
    if is_float(arg):
        data = float(arg)
    else:
        if not os.path.isfile(arg):
            raise ValueError('Input file {} does not exist.'.format(arg))

        data = load_matrix_in_any_format(arg)
        logging.info('Loaded {} of shape {} and data_type {}.'.format(
            arg, data.shape, data.dtype))

        if data.ndim > 2:
            logging.warning('{} has {} dimensions, be careful.'.format(
                arg, data.ndim))
        elif data.ndim < 2:
            raise ValueError('{} has {} dimensions, not valid.'.format(
                arg, data.ndim))

    return data
コード例 #4
0
def load_matrix(arg):
    if is_float(arg):
        matrix = float(arg)
    else:
        if not os.path.isfile(arg):
            raise ValueError('Input file {} does not exist.'.format(arg))

        data = load_matrix_in_any_format(arg).astype(np.float64)
        matrix = nib.Nifti1Image(data, np.eye(4))
        logging.info('Loaded {} of shape {} and data_type {}.'.format(
            arg, data.shape, data.dtype))

        if data.ndim > 2:
            logging.warning('{} has {} dimensions, be careful.'.format(
                arg, data.ndim))
        elif data.ndim < 2:
            raise ValueError('{} has {} dimensions, not valid.'.format(
                arg, data.ndim))

    return matrix
コード例 #5
0
def load_img(arg):
    if is_float(arg):
        img = float(arg)
        dtype = np.float64
    else:
        if not os.path.isfile(arg):
            raise ValueError('Input file {} does not exist.'.format(arg))
        img = nib.load(arg)
        shape = img.header.get_data_shape()
        dtype = img.header.get_data_dtype()
        logging.info('Loaded {} of shape {} and data_type {}.'.format(
            arg, shape, dtype))

        if len(shape) > 3:
            logging.warning('{} has {} dimensions, be careful.'.format(
                arg, len(shape)))
        elif len(shape) < 3:
            raise ValueError('{} has {} dimensions, not valid.'.format(
                arg, len(shape)))

    return img, dtype
コード例 #6
0
ファイル: operations.py プロジェクト: arnaudbore/scilpy
def _validate_float(x):
    """Make sure that the input can be casted to a float."""
    if not is_float(x):
        logging.error('The input must be float/int for this operation.')
        raise ValueError
コード例 #7
0
def main():
    parser = _build_arg_parser()
    args = parser.parse_args()

    if args.verbose:
        logging.basicConfig(level=logging.INFO)

    assert_outputs_exist(parser, args, args.out_image)

    # Binary operations require specific verifications
    binary_op = [
        'union', 'intersection', 'difference', 'invert', 'dilation', 'erosion',
        'closing', 'opening'
    ]

    if args.operation not in OPERATIONS.keys():
        parser.error('Operation {} not implement.'.format(args.operation))

    # Find at least one image for reference
    for input_arg in args.in_images:
        if not is_float(input_arg):
            ref_img = nib.load(input_arg)
            mask = np.zeros(ref_img.shape)
            break

    # Load all input masks.
    input_data = []
    for input_arg in args.in_images:
        if not is_float(input_arg) and \
                not is_header_compatible(ref_img, input_arg):
            parser.error('Inputs do not have a compatible header.')
        data = load_data(input_arg)

        if isinstance(data, np.ndarray) and \
            data.dtype != ref_img.get_data_dtype() and \
                not args.data_type:
            parser.error('Inputs do not have a compatible data type.\n'
                         'Use --data_type to specify output datatype.')
        if args.operation in binary_op and isinstance(data, np.ndarray):
            unique = np.unique(data)
            if not len(unique) <= 2:
                parser.error('Binary operations can only be performed with '
                             'binary masks')

            if len(unique) == 2 and not (unique == [0, 1]).all():
                logging.warning('Input data for binary operation are not '
                                'binary arrays, will be converted.\n'
                                'Non-zeros will be set to ones.')
                data[data != 0] = 1

        if isinstance(data, np.ndarray):
            data = data.astype(np.float64)
            mask[data > 0] = 1
        input_data.append(data)

    if args.operation == 'convert' and not args.data_type:
        parser.error('Convert operation must be used with --data_type.')

    try:
        output_data = OPERATIONS[args.operation](input_data)
    except ValueError:
        logging.error('{} operation failed.'.format(
            args.operation.capitalize()))
        return

    if args.data_type:
        output_data = output_data.astype(args.data_type)
        ref_img.header.set_data_dtype(args.data_type)
    else:
        output_data = output_data.astype(ref_img.get_data_dtype())

    if args.exclude_background:
        output_data[mask == 0] = 0

    new_img = nib.Nifti1Image(output_data,
                              ref_img.affine,
                              header=ref_img.header)
    nib.save(new_img, args.out_image)
コード例 #8
0
def main():
    parser = _build_arg_parser()
    args = parser.parse_args()

    if args.verbose:
        logging.basicConfig(level=logging.INFO)

    assert_outputs_exist(parser, args, args.out_matrix)

    # Binary operations require specific verifications
    binary_op = ['union', 'intersection', 'difference', 'invert']

    if args.operation not in OPERATIONS.keys():
        parser.error('Operation {} not implemented.'.format(args.operation))

    # Find at least one matrix for reference
    for input_arg in args.in_matrices:
        found_ref = False
        if not is_float(input_arg):
            ref_data = load_matrix_in_any_format(input_arg)
            ref_matrix = nib.Nifti1Image(ref_data, np.eye(4))
            mask = np.zeros(ref_data.shape)
            found_ref = True
            break

    if not found_ref:
        raise ValueError('Requires at least one matrix.')

    # Load all input matrices
    input_matrices = []
    for input_arg in args.in_matrices:
        matrix = load_matrix(input_arg)

        if args.operation in binary_op and isinstance(matrix, nib.Nifti1Image):
            data = matrix.get_fdata(dtype=np.float64)
            unique = np.unique(data)
            if not len(unique) <= 2:
                parser.error('Binary operations can only be performed with '
                             'binary masks.')

            if len(unique) == 2 and not (unique == [0, 1]).all():
                logging.warning('Input data for binary operation are not '
                                'binary array, will be converted.\n'
                                'Non-zeros will be set to ones.')
                data[data != 0] = 1

        if isinstance(matrix, nib.Nifti1Image):
            data = matrix.get_fdata(dtype=np.float64)
            mask[data > 0] = 1
        input_matrices.append(matrix)

    if args.operation == 'convert' and not args.data_type:
        parser.error('Convert operation must be used with --data_type.')

    # Perform the request operation
    try:
        output_data = OPERATIONS[args.operation](input_matrices, ref_matrix)
    except ValueError:
        logging.error('{} operation failed.'.format(
            args.operation.capitalize()))
        return

    # Cast if needed
    if args.data_type:
        output_data = output_data.astype(args.data_type)
    else:
        output_data = output_data.astype(np.float64)

    if args.exclude_background:
        output_data[mask == 0] = 0

    # Saving in the right format
    save_matrix_in_any_format(args.out_matrix, output_data)