示例#1
0
def test_resample_outvalue():
    # Test resampling with different modes, constant values, datatypes, orders

    def func(xyz):
        return xyz + np.asarray([1, 0, 0])

    coordmap = vox2mni(np.eye(4))
    arr = np.arange(3 * 3 * 3).reshape(3, 3, 3)
    aff = np.eye(4)
    aff[0, 3] = 1.  # x translation
    for mapping, dt, order in product(
        [aff, func],
        [np.int8, np.intp, np.int32, np.int64, np.float32, np.float64],
        [0, 1, 3]):
        img = Image(arr.astype(dt), coordmap)
        # Test constant value of 0
        img2 = resample(img,
                        coordmap,
                        mapping,
                        img.shape,
                        order=order,
                        mode='constant',
                        cval=0.)
        exp_arr = np.zeros(arr.shape)
        exp_arr[:-1, :, :] = arr[1:, :, :]
        assert_array_almost_equal(img2.get_data(), exp_arr)
        # Test constant value of 1
        img2 = resample(img,
                        coordmap,
                        mapping,
                        img.shape,
                        order=order,
                        mode='constant',
                        cval=1.)
        exp_arr[-1, :, :] = 1
        assert_array_almost_equal(img2.get_data(), exp_arr)
        # Test nearest neighbor
        img2 = resample(img,
                        coordmap,
                        mapping,
                        img.shape,
                        order=order,
                        mode='nearest')
        exp_arr[-1, :, :] = arr[-1, :, :]
        assert_array_almost_equal(img2.get_data(), exp_arr)
    # Test img2img
    target_coordmap = vox2mni(aff)
    target = Image(arr, target_coordmap)
    img2 = resample_img2img(img, target, 3, 'nearest')
    assert_array_almost_equal(img2.get_data(), exp_arr)
    img2 = resample_img2img(img, target, 3, 'constant', cval=1.)
    exp_arr[-1, :, :] = 1
    assert_array_almost_equal(img2.get_data(), exp_arr)
示例#2
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-1',
                        '--roi1',
                        type=str,
                        help='Filename of the first ROI image')
    parser.add_argument('-2',
                        '--roi2',
                        type=str,
                        help='Filename of the second ROI image')
    parser.add_argument('-c',
                        '--coord-image',
                        type=str,
                        help='Filename of the coordinates image')
    parser.add_argument('-o',
                        '--output-file',
                        type=str,
                        help='Filename to use for combined ROIs')

    args = parser.parse_args()
    print(args)

    # check that both images exist
    if not os.path.exists(args.roi1):
        print("File '" + args.roi1 + "' does not exist")
    if not os.path.exists(args.roi2):
        print("File '" + args.roi2 + "' does not exist")
    if not os.path.exists(args.coord_image):
        print("File '" + args.coord_image)

    # load both images for the purpose of checking coordinates
    roi1, coords1 = mil.loadBOLD(args.roi1)
    roi2, coords2 = mil.loadBOLD(args.roi2)
    img, imgCoords = mil.loadBOLD(args.coord_image)

    print("roi1", roi1.shape)
    print("roi2", roi2.shape)
    print("coords", img.shape)

    # perform the OR-ing of the 2 rois
    addingImgs = BinaryMaths()
    addingImgs.inputs.in_file = args.roi1
    addingImgs.inputs.operand_file = args.roi2
    addingImgs.inputs.operation = "max"
    addingImgs.inputs.out_file = args.output_file
    addingImgs.run()

    # resample the new roi to be in the coordinate frame of the coordinate image
    jointRoi = load_image(args.output_file)
    coordsImg = load_image(args.coord_image)
    print("joint rois", jointRoi.get_data().shape)
    newRoiImg = resample_img2img(jointRoi, coordsImg, order=0)
    save_image(newRoiImg, args.output_file)
示例#3
0
def test_resample_outvalue():
    # Test resampling with different modes, constant values, datatypes, orders

    def func(xyz):
        return xyz + np.asarray([1,0,0])

    coordmap =  vox2mni(np.eye(4))
    arr = np.arange(3 * 3 * 3).reshape(3, 3, 3)
    aff = np.eye(4)
    aff[0, 3] = 1.  # x translation
    for mapping, dt, order in product(
        [aff, func],
        [np.int8, np.intp, np.int32, np.int64, np.float32, np.float64],
        [0, 1, 3]):
        img = Image(arr.astype(dt), coordmap)
        # Test constant value of 0
        img2 = resample(img, coordmap, mapping, img.shape,
                        order=order, mode='constant', cval=0.)
        exp_arr = np.zeros(arr.shape)
        exp_arr[:-1, :, :] = arr[1:, :, :]
        assert_array_almost_equal(img2.get_data(), exp_arr)
        # Test constant value of 1
        img2 = resample(img, coordmap, mapping, img.shape,
                        order=order, mode='constant', cval=1.)
        exp_arr[-1, :, :] = 1
        assert_array_almost_equal(img2.get_data(), exp_arr)
        # Test nearest neighbor
        img2 = resample(img, coordmap, mapping, img.shape,
                        order=order, mode='nearest')
        exp_arr[-1, :, :] = arr[-1, :, :]
        assert_array_almost_equal(img2.get_data(), exp_arr)
    # Test img2img
    target_coordmap = vox2mni(aff)
    target = Image(arr, target_coordmap)
    img2 = resample_img2img(img, target, 3, 'nearest')
    assert_array_almost_equal(img2.get_data(), exp_arr)
    img2 = resample_img2img(img, target, 3, 'constant', cval=1.)
    exp_arr[-1, :, :] = 1
    assert_array_almost_equal(img2.get_data(), exp_arr)
示例#4
0
    def run(self, masterFile, inputFiles, outputDirectory, spacing, dimensions,
            likefreesurfer, nii):
        '''
    Performs the equalization
    '''

        # sanity checks
        outputDirectory = os.path.normpath(outputDirectory)
        # prepare the output directory
        if os.path.exists(outputDirectory):
            c.error('The output directory already exists!')
            c.error('Aborting..')
            sys.exit(2)
        # create the output directory
        os.mkdir(outputDirectory)

        # MASTER
        masterFile = os.path.normpath(masterFile)
        # read the master
        master = io.readImage(masterFile)
        c.info('MASTER IMAGE: ' + str(masterFile))

        # INPUTS
        for i in range(len(inputFiles)):
            inputFiles[i] = os.path.normpath(inputFiles[i])
            c.info('INPUT IMAGE ' + str(i + 1) + ': ' + str(inputFiles[i]))

        # print more info
        c.info('OUTPUT DIRECTORY: ' + str(outputDirectory))

        if likefreesurfer:
            spacing = '1,1,1'
            dimensions = '256,256,256'

        if spacing != 'no':
            c.info('SET SPACINGS: ' + str(spacing))

        if dimensions != 'no':
            c.info('SET DIMENSIONS: ' + str(dimensions))

        # re-sample master to obtain an isotropic dataset
        master = self.aniso2iso(master, spacing, dimensions)
        masterFileBasename = os.path.split(masterFile)[1]
        masterFileBasenameWithoutExt = os.path.splitext(masterFileBasename)[0]

        if not nii:
            masterOutputFileName = os.path.join(outputDirectory,
                                                masterFileBasename)
        else:
            masterOutputFileName = os.path.join(
                outputDirectory, masterFileBasenameWithoutExt) + '.nii'
        io.saveImage(masterOutputFileName, master)

        # equalize all images to the master
        for i in range(len(inputFiles)):
            currentInputFile = inputFiles[i]

            c.info('Equalizing ' + str(currentInputFile) + ' to ' +
                   str(masterFile) + "...")

            # load the image
            currentImage = io.readImage(currentInputFile)
            currentImageHeader = currentImage.header
            c.info('    old spacing: ' + str(currentImageHeader.get_zooms()))
            c.info('    old dimensions: ' + str(currentImage.shape[:3]))

            # now resample
            resampledImage = resampler.resample_img2img(currentImage, master)

            # .. and save it
            currentInputFileBasename = os.path.split(currentInputFile)[1]
            currentInputFileBasenameWithoutExt = os.path.splitext(
                currentInputFileBasename)[0]
            if not nii:
                outputFileName = os.path.join(outputDirectory,
                                              currentInputFileBasename)
            else:
                outputFileName = os.path.join(
                    outputDirectory, currentInputFileBasenameWithoutExt)

            savedImage = io.saveImage(outputFileName, resampledImage)
            #c.info( '    new spacing: ' + str( savedImageHeader.get_zooms() ) )
            c.info('    new dimensions: ' + str(savedImage.shape[:3]))

        c.info('All done!')
示例#5
0
def test_resample_img2img():
    fimg = load_image(funcfile)
    aimg = load_image(anatfile)
    resimg = resample_img2img(fimg, fimg)
    yield assert_true, np.allclose(resimg.get_data(), fimg.get_data())
    yield assert_raises, ValueError, resample_img2img, fimg, aimg
示例#6
0
def test_resample_img2img():
    fimg = load_image(funcfile)
    aimg = load_image(anatfile)
    resimg = resample_img2img(fimg, fimg)
    yield assert_true, np.allclose(np.asarray(resimg), np.asarray(fimg))
    yield assert_raises, ValueError, resample_img2img, fimg, aimg