Esempio n. 1
0
def main():
    # parse cmd arguments
    parser = getParser()
    parser.parse_args()
    args = getArguments(parser)
    
    # prepare logger
    logger = Logger.getInstance()
    if args.debug: logger.setLevel(logging.DEBUG)
    elif args.verbose: logger.setLevel(logging.INFO)
    
    # build output image name
    image_bg_name = args.folder + '/' + args.mask.split('/')[-1][:-4] + '.bg'
    image_bg_name += args.mask.split('/')[-1][-4:]
        
    # check if output image exists
    if not args.force:
        if os.path.exists(image_bg_name):
            logger.warning('The output image {} already exists. Breaking.'.format(image_bg_name))
            exit(1)
    
    # load mask
    logger.info('Loading mask {}...'.format(args.mask))
    try: 
        mask_image = load(args.mask)
        mask_image_data = numpy.squeeze(mask_image.get_data()).astype(scipy.bool_)
    except ImageFileError as e:
        logger.critical('The mask image does not exist or its file type is unknown.')
        raise ArgumentError('The mask image does not exist or its file type is unknown.', e)  
    
    # array of indices to access desired slices
    sls = [(slice(1), slice(None), slice(None)),
           (slice(-1, None), slice(None), slice(None)),
           (slice(None), slice(1), slice(None)),
           (slice(None), slice(-1, None), slice(None)),
           (slice(None), slice(None), slice(1)),
           (slice(None), slice(None), slice(-1, None))]
    
    # security check
    logger.info('Determine if the slices are not intersection with the reference liver mask...')
    for sl in sls:
        if not 0 == len(mask_image_data[sl].nonzero()[0]):
            logger.critical('Reference mask reaches till the image border.')
            raise ArgumentError('Reference mask reaches till the image border.')
        
    # create and save background marker image
    logger.info('Creating background marker image...')
    image_bg_data = scipy.zeros(mask_image_data.shape, dtype=scipy.bool_)
    for sl in sls:
        image_bg_data[sl] = True
    
    logger.info('Saving background marker image...')
    mask_image.get_header().set_data_dtype(scipy.int8)
    save(image_like(image_bg_data, mask_image), image_bg_name)
    
    logger.info('Successfully terminated.')
Esempio n. 2
0
def main():
    # parse cmd arguments
    parser = getParser()
    parser.parse_args()
    args = getArguments(parser)

    # prepare logger
    logger = Logger.getInstance()
    if args.debug: logger.setLevel(logging.DEBUG)
    elif args.verbose: logger.setLevel(logging.INFO)

    # build output image name
    image_fg_name = args.folder + '/' + args.mask.split('/')[-1][:-4] + '.fg'
    image_fg_name += args.mask.split('/')[-1][-4:]
    image_bg_name = args.folder + '/' + args.mask.split('/')[-1][:-4] + '.bg'
    image_bg_name += args.mask.split('/')[-1][-4:]

    # check if output image exists
    if not args.force:
        if os.path.exists(image_fg_name):
            logger.warning(
                'The output image {} already exists. Breaking.'.format(
                    image_fg_name))
            exit(1)
        elif os.path.exists(image_bg_name):
            logger.warning(
                'The output image {} already exists. Breaking.'.format(
                    image_bg_name))
            exit(1)

    # load mask
    logger.info('Loading mask {}...'.format(args.mask))

    try:
        mask_image = load(args.mask)
        mask_image_data = numpy.squeeze(mask_image.get_data()).astype(
            scipy.bool_)
    except ImageFileError as e:
        logger.critical(
            'The mask image does not exist or its file type is unknown.')
        raise ArgumentError(
            'The mask image does not exist or its file type is unknown.', e)

    # erode mask stepwise
    logger.info('Step-wise reducing mask to find center...')
    mask_remains = mask_image_data.copy()
    while (True):
        mask_remains_next = ndimage.binary_erosion(mask_remains, iterations=2)
        if 0 == len(mask_remains_next.nonzero()[0]):
            break
        mask_remains = mask_remains_next

    # extract one of the remaining voxels
    voxels = mask_remains.nonzero()
    marker = (voxels[0][0], voxels[1][0], voxels[2][0])

    logger.debug('Extracted foreground seed is {}.'.format(marker))

    # check suitability of corners as background markers
    logger.info(
        'Checking if the corners are suitable background seed candidates...')
    if True == mask_image_data[0,0,0] or \
       True == mask_image_data[-1,0,0] or \
       True == mask_image_data[0,-1,0] or \
       True == mask_image_data[0,0,-1] or \
       True == mask_image_data[-1,-1,0] or \
       True == mask_image_data[-1,0,-1] or \
       True == mask_image_data[0,-1,-1] or \
       True == mask_image_data[-1,-1,-1]:
        logger.critical(
            'The corners of the image do not correspond to background voxels.')
        raise ArgumentError(
            'The corners of the image do not correspond to background voxels.')

    # create and save foreground marker image
    logger.info('Creating foreground marker image...')
    image_fg_data = scipy.zeros(mask_image_data.shape, dtype=scipy.bool_)
    image_fg_data[marker[0], marker[1], marker[2]] = True

    logger.info('Saving foreground marker image...')
    mask_image.get_header().set_data_dtype(scipy.int8)
    save(image_like(image_fg_data, mask_image), image_fg_name)

    # create and save background marker image
    logger.info('Creating background marker image...')
    image_bg_data = scipy.zeros(mask_image_data.shape, dtype=scipy.bool_)
    image_bg_data[0, 0, 0] = True
    image_bg_data[-1, 0, 0] = True
    image_bg_data[0, -1, 0] = True
    image_bg_data[0, 0, -1] = True
    image_bg_data[-1, -1, 0] = True
    image_bg_data[-1, 0, -1] = True
    image_bg_data[0, -1, -1] = True
    image_bg_data[-1, -1, -1] = True

    logger.info('Saving background marker image...')
    mask_image.get_header().set_data_dtype(scipy.int8)
    save(image_like(image_bg_data, mask_image), image_bg_name)

    logger.info('Successfully terminated.')
def main():
    # parse cmd arguments
    parser = getParser()
    parser.parse_args()
    args = getArguments(parser)
    
    # prepare logger
    logger = Logger.getInstance()
    if args.debug: logger.setLevel(logging.DEBUG)
    elif args.verbose: logger.setLevel(logging.INFO)
    
    # build output image name
    image_fg_name = args.folder + '/' + args.mask.split('/')[-1][:-4] + '.fg'
    image_fg_name += args.mask.split('/')[-1][-4:]
    image_bg_name = args.folder + '/' + args.mask.split('/')[-1][:-4] + '.bg'
    image_bg_name += args.mask.split('/')[-1][-4:]
        
    # check if output image exists
    if not args.force:
        if os.path.exists(image_fg_name):
            logger.warning('The output image {} already exists. Breaking.'.format(image_fg_name))
            exit(1)
        elif os.path.exists(image_bg_name):
            logger.warning('The output image {} already exists. Breaking.'.format(image_bg_name))
            exit(1)
    
    # load mask
    logger.info('Loading mask {}...'.format(args.mask))
    
    try: 
        mask_image = load(args.mask)
        mask_image_data = numpy.squeeze(mask_image.get_data()).astype(scipy.bool_)
    except ImageFileError as e:
        logger.critical('The mask image does not exist or its file type is unknown.')
        raise ArgumentError('The mask image does not exist or its file type is unknown.', e)  
    
    # erode mask stepwise
    logger.info('Step-wise reducing mask to find center...')
    mask_remains = mask_image_data.copy()
    while (True):
        mask_remains_next = ndimage.binary_erosion(mask_remains, iterations=2)
        if 0 == len(mask_remains_next.nonzero()[0]):
            break
        mask_remains = mask_remains_next
    
    # extract one of the remaining voxels
    voxels = mask_remains.nonzero()
    marker = (voxels[0][0], voxels[1][0], voxels[2][0])
    
    logger.debug('Extracted foreground seed is {}.'.format(marker))
    
    # check suitability of corners as background markers
    logger.info('Checking if the corners are suitable background seed candidates...')
    if True == mask_image_data[0,0,0] or \
       True == mask_image_data[-1,0,0] or \
       True == mask_image_data[0,-1,0] or \
       True == mask_image_data[0,0,-1] or \
       True == mask_image_data[-1,-1,0] or \
       True == mask_image_data[-1,0,-1] or \
       True == mask_image_data[0,-1,-1] or \
       True == mask_image_data[-1,-1,-1]:
        logger.critical('The corners of the image do not correspond to background voxels.')
        raise ArgumentError('The corners of the image do not correspond to background voxels.')
    
    # create and save foreground marker image
    logger.info('Creating foreground marker image...')
    image_fg_data = scipy.zeros(mask_image_data.shape, dtype=scipy.bool_)
    image_fg_data[marker[0], marker[1], marker[2]] = True

    logger.info('Saving foreground marker image...')
    mask_image.get_header().set_data_dtype(scipy.int8)
    save(image_like(image_fg_data, mask_image), image_fg_name)

    # create and save background marker image
    logger.info('Creating background marker image...')
    image_bg_data = scipy.zeros(mask_image_data.shape, dtype=scipy.bool_)
    image_bg_data[0,0,0] = True
    image_bg_data[-1,0,0] = True
    image_bg_data[0,-1,0] = True
    image_bg_data[0,0,-1] = True
    image_bg_data[-1,-1,0] = True
    image_bg_data[-1,0,-1] = True
    image_bg_data[0,-1,-1] = True
    image_bg_data[-1,-1,-1] = True
    
    logger.info('Saving background marker image...')
    mask_image.get_header().set_data_dtype(scipy.int8)
    save(image_like(image_bg_data, mask_image), image_bg_name)
    
    logger.info('Successfully terminated.')
def main():
    # parse cmd arguments
    parser = getParser()
    parser.parse_args()
    args = getArguments(parser)
    
    # prepare logger
    logger = Logger.getInstance()
    if args.debug: logger.setLevel(logging.DEBUG)
    elif args.verbose: logger.setLevel(logging.INFO)
    
    # iterate over input images
    for image in args.images:
        
        # build output image name
        image_real_name = image.split('/')[-1][:-4] + '_real' + image.split('/')[-1][-4:]
        image_imag_name = image.split('/')[-1][:-4] + '_imag' + image.split('/')[-1][-4:]
        
        # check if output images exists
        if not args.force:
            if os.path.exists(image_real_name):
                logger.warning('The output image {} already exists. Skipping this step.'.format(image_real_name))
                continue
            elif os.path.exists(image_imag_name):
                logger.warning('The output image {} already exists. Skipping this step.'.format(image_imag_name))
                continue
        
        # load image using nibabel
        logger.info('Loading image {} using NiBabel...'.format(image))
        image_original = load(image)
        
        # get and prepare image data
        image_original_data = scipy.squeeze(image_original.get_data())
        
        # apply the discrete fast Fourier transformation
        logger.info('Executing the discrete fast Fourier transformation...')
        image_fft_data = scipy.fftpack.fftn(image_original_data)
        
        # transform to logarithmic scale
        logger.info('To logarithmic space...')
        image_real_data = image_fft_data.real
        print image_real_data.min(), image_real_data.max()
        image_real_data = image_real_data + abs(image_real_data.min())
        constant = 65535./(math.log(1 + image_real_data.max())) # scale by 0.0001, log and then scale to fir uint16
        myfunc = lambda x: constant * math.log(1 + x * 0.0001)
        new_func = numpy.vectorize(myfunc)
        logger.info('Apply...')
        image_real_data = new_func(image_real_data)
        print image_real_data.min(), image_real_data.max()
        image_imag_data = image_fft_data.imag
        
        # save resulting images
        logger.info('Saving resulting images real part as {} in the same format as input image, only with data-type float32...'.format(image_real_name))
        image_real = image_like(image_real_data, image_original)
        image_real.get_header().set_data_dtype(scipy.uint16)
        save(image_real, image_real_name)
        logger.info('Saving resulting images real part as {} in the same format as input image, only with data-type float32...'.format(image_imag_name))
        image_imag = image_like(image_imag_data, image_original)
        image_imag.get_header().set_data_dtype(scipy.float32)
        save(image_imag, image_imag_name)
    
    logger.info('Successfully terminated.')
def main():
    # parse cmd arguments
    parser = getParser()
    parser.parse_args()
    args = getArguments(parser)

    # prepare logger
    logger = Logger.getInstance()
    if args.debug:
        logger.setLevel(logging.DEBUG)
    elif args.verbose:
        logger.setLevel(logging.INFO)

    # iterate over input images
    for image in args.images:

        # build output image name
        image_real_name = image.split("/")[-1][:-4] + "_real" + image.split("/")[-1][-4:]
        image_imag_name = image.split("/")[-1][:-4] + "_imag" + image.split("/")[-1][-4:]

        # check if output images exists
        if not args.force:
            if os.path.exists(image_real_name):
                logger.warning("The output image {} already exists. Skipping this step.".format(image_real_name))
                continue
            elif os.path.exists(image_imag_name):
                logger.warning("The output image {} already exists. Skipping this step.".format(image_imag_name))
                continue

        # load image using nibabel
        logger.info("Loading image {} using NiBabel...".format(image))
        image_original = load(image)

        # get and prepare image data
        image_original_data = scipy.squeeze(image_original.get_data())

        # apply the discrete fast Fourier transformation
        logger.info("Executing the discrete fast Fourier transformation...")
        image_fft_data = scipy.fftpack.fftn(image_original_data)

        # transform to logarithmic scale
        logger.info("To logarithmic space...")
        image_real_data = image_fft_data.real
        print image_real_data.min(), image_real_data.max()
        image_real_data = image_real_data + abs(image_real_data.min())
        constant = 65535.0 / (math.log(1 + image_real_data.max()))  # scale by 0.0001, log and then scale to fir uint16
        myfunc = lambda x: constant * math.log(1 + x * 0.0001)
        new_func = numpy.vectorize(myfunc)
        logger.info("Apply...")
        image_real_data = new_func(image_real_data)
        print image_real_data.min(), image_real_data.max()
        image_imag_data = image_fft_data.imag

        # save resulting images
        logger.info(
            "Saving resulting images real part as {} in the same format as input image, only with data-type float32...".format(
                image_real_name
            )
        )
        image_real = image_like(image_real_data, image_original)
        image_real.get_header().set_data_dtype(scipy.uint16)
        save(image_real, image_real_name)
        logger.info(
            "Saving resulting images real part as {} in the same format as input image, only with data-type float32...".format(
                image_imag_name
            )
        )
        image_imag = image_like(image_imag_data, image_original)
        image_imag.get_header().set_data_dtype(scipy.float32)
        save(image_imag, image_imag_name)

    logger.info("Successfully terminated.")