コード例 #1
0
def test_toFnirt():
    def check(got, exp):
        tol = dict(atol=1e-5, rtol=1e-5)
        assert np.all(np.isclose(got.data, exp.data, **tol))
        assert got.src.sameSpace(exp.src)
        assert got.ref.sameSpace(exp.ref)
        assert got.srcSpace == 'fsl'
        assert got.refSpace == 'fsl'

    basefield, xform = _random_affine_field()
    src = basefield.src
    ref = basefield.ref

    spaces = it.permutations(('voxel', 'fsl', 'world'), 2)

    for from_, to in spaces:
        field = nonlinear.convertDeformationSpace(basefield, from_, to)
        got = fnirt.toFnirt(field)
        check(got, basefield)

    src = fslimage.Image(op.join(datadir, 'src'))
    ref = fslimage.Image(op.join(datadir, 'ref'))
    coef = fnirt.readFnirt(op.join(datadir, 'coefficientfield'), src, ref)
    got = fnirt.toFnirt(coef)
    check(got, coef)
コード例 #2
0
def test_applyDeformation_altref():
    src2ref = affine.compose(
        np.random.randint(2, 5, 3),
        np.random.randint(1, 10, 3),
        np.random.random(3))
    ref2src = affine.invert(src2ref)

    srcdata = np.random.randint(1, 65536, (10, 10, 10))
    refdata = np.random.randint(1, 65536, (10, 10, 10))

    src   = fslimage.Image(srcdata)
    ref   = fslimage.Image(refdata, xform=src2ref)
    field = _affine_field(src, ref, ref2src, 'world', 'world')

    altrefxform = affine.concat(
        src2ref,
        affine.scaleOffsetXform([1, 1, 1], [5, 0, 0]))

    altref = fslimage.Image(refdata, xform=altrefxform)

    expect, xf = resample.resampleToReference(
        src, altref, matrix=src2ref, order=1, mode='constant', cval=0)
    result = nonlinear.applyDeformation(
        src, field, ref=altref, order=1, mode='constant', cval=0)

    # boundary voxels can get truncated
    # (4 is the altref-ref overlap boundary)
    expect[4, :, :] = 0
    result[4, :, :] = 0
    expect = expect[1:-1, 1:-1, 1:-1]
    result = result[1:-1, 1:-1, 1:-1]

    assert np.all(np.isclose(expect, result))
コード例 #3
0
ファイル: test_x5.py プロジェクト: physimals/fslpy
def test_readWriteNonLinearX5():
    datadir = op.join(op.dirname(__file__), 'testdata', 'nonlinear')
    dffile = op.join(datadir, 'displacementfield.nii.gz')
    srcfile = op.join(datadir, 'src.nii.gz')
    reffile = op.join(datadir, 'ref.nii.gz')

    src = fslimage.Image(srcfile)
    ref = fslimage.Image(reffile)
    dfield = fnirt.readFnirt(dffile, src, ref)
    wdfield = nonlinear.convertDeformationSpace(dfield, 'world', 'world')

    with tempdir.tempdir():

        # field must be world->world
        with pytest.raises(x5.X5Error):
            x5.writeNonLinearX5('nonlinear.x5', dfield)

        x5.writeNonLinearX5('nonlinear.x5', wdfield)

        gotdfield = x5.readNonLinearX5('nonlinear.x5')

        assert gotdfield.src.sameSpace(src)
        assert gotdfield.ref.sameSpace(ref)
        assert gotdfield.srcSpace == wdfield.srcSpace
        assert gotdfield.refSpace == wdfield.refSpace
        assert gotdfield.deformationType == wdfield.deformationType
        assert np.all(np.isclose(gotdfield.data, wdfield.data))

        with h5py.File('nonlinear.x5', 'r') as f:
            assert f.attrs['Type'] == 'nonlinear'
            _check_metadata(f)
            _check_deformation(f['/Transform'], wdfield)
            _check_space(f['/A'], ref)
            _check_space(f['/B'], src)
コード例 #4
0
ファイル: test_fsl_apply_x5.py プロジェクト: physimals/fslpy
def test_linear_altref(seed):
    with tempdir.tempdir():

        src2ref = affine.scaleOffsetXform([1, 1, 1], [5, 5, 5])
        altv2w = affine.scaleOffsetXform([1, 1, 1], [10, 10, 10])

        srcdata = np.random.randint(1, 65536, (10, 10, 10))
        src = fslimage.Image(srcdata, xform=np.eye(4))
        ref = fslimage.Image(src.data, xform=src2ref)
        altref = fslimage.Image(src.data, xform=altv2w)

        src.save('src')
        ref.save('ref')
        altref.save('altref')

        x5.writeLinearX5('xform.x5', src2ref, src, ref)

        fsl_apply_x5.main('src xform.x5 out -r altref'.split())

        result = fslimage.Image('out')
        expect = np.zeros(srcdata.shape)
        expect[:5, :5, :5] = srcdata[5:, 5:, 5:]

        assert result.sameSpace(altref)
        assert np.all(result.data == expect)
コード例 #5
0
def test_convert_fnirt_coefficient_field():

    datadir = op.join(op.dirname(__file__), '..', 'test_transform', 'testdata',
                      'nonlinear')
    srcfile = op.join(datadir, 'src.nii.gz')
    reffile = op.join(datadir, 'ref.nii.gz')
    cffile = op.join(datadir, 'coefficientfield.nii.gz')
    dffile = op.join(datadir, 'displacementfield.nii.gz')

    with tempdir.tempdir():

        # nii -> x5
        fsl_convert_x5.main('fnirt -s {} -r {} {} coef.x5'.format(
            srcfile, reffile, cffile).split())

        # x5 -> nii
        fsl_convert_x5.main('fnirt coef.x5 coef.nii.gz'.split())

        src = fslimage.Image(srcfile)
        ref = fslimage.Image(reffile)
        df = fnirt.readFnirt(dffile, src, ref)
        dfnii = fnirt.readFnirt('coef.nii.gz', src, ref)

        assert dfnii.sameSpace(df)
        assert dfnii.src.sameSpace(src)
        assert dfnii.ref.sameSpace(ref)

        assert dfnii.srcSpace == df.srcSpace
        assert dfnii.refSpace == df.refSpace
        assert dfnii.deformationType == 'relative'

        diff = np.abs(dfnii.data - df.data)
        tols = {'rtol': 1e-5, 'atol': 1e-5}
        assert np.all(np.isclose(dfnii.data, df.data, **tols))
コード例 #6
0
ファイル: test_flirt.py プロジェクト: physimals/fslpy
def test_sformToFlirtMatrix():
    testfile = op.join(datadir, 'test_transform_test_flirtMatrixToSform.txt')
    lines = readlines(testfile)
    ntests = len(lines) // 18

    for i in range(ntests):
        tlines = lines[i * 18:i * 18 + 18]
        srcShape = [int(w) for w in tlines[0].split()]
        srcXform = np.genfromtxt(tlines[1:5])
        refShape = [int(w) for w in tlines[5].split()]
        refXform = np.genfromtxt(tlines[6:10])
        expected = np.genfromtxt(tlines[10:14])
        srcXformOvr = np.genfromtxt(tlines[14:18])

        srcImg1 = fslimage.Image(np.zeros(srcShape), xform=srcXform)
        srcImg2 = fslimage.Image(np.zeros(srcShape), xform=srcXform)
        refImg = fslimage.Image(np.zeros(refShape), xform=refXform)

        srcImg2.voxToWorldMat = srcXformOvr

        result1 = flirt.sformToFlirtMatrix(srcImg1, refImg, srcXformOvr)
        result2 = flirt.sformToFlirtMatrix(srcImg2, refImg)

        assert np.all(np.isclose(result1, expected))
        assert np.all(np.isclose(result2, expected))
コード例 #7
0
def test_convert_fnirt_deformation_field():

    datadir = op.join(op.dirname(__file__), '..', 'test_transform', 'testdata',
                      'nonlinear')
    srcfile = op.join(datadir, 'src.nii.gz')
    reffile = op.join(datadir, 'ref.nii.gz')
    dffile = op.join(datadir, 'displacementfield.nii.gz')

    with tempdir.tempdir():

        # nii -> x5
        fsl_convert_x5.main('fnirt -s {} -r {} {} disp.x5'.format(
            srcfile, reffile, dffile).split())

        # x5 -> nii
        fsl_convert_x5.main('fnirt disp.x5 disp.nii.gz'.split())

        src = fslimage.Image(srcfile)
        ref = fslimage.Image(reffile)
        df = fnirt.readFnirt(dffile, src, ref)
        dfnii = fnirt.readFnirt('disp.nii.gz', src, ref)

        assert dfnii.src.sameSpace(src)
        assert dfnii.ref.sameSpace(ref)
        assert dfnii.srcSpace == df.srcSpace
        assert dfnii.refSpace == df.refSpace
        assert dfnii.deformationType == df.deformationType
        assert np.all(np.isclose(dfnii.data, df.data))
コード例 #8
0
def _test_transformCoords(panel, overlayList, displayCtx):
    displayCtx = panel.displayCtx
    mesh = fslvtk.VTKMesh(op.join(datadir, 'mesh_l_thal.vtk'))
    ref = fslimage.Image(op.join(datadir, 'mesh_ref.nii.gz'))

    # resample to something other than 1mm^3
    # so display/voxel coord systems are different
    ref, xform = resample.resampleToPixdims(ref, [1.5, 1.5, 1.5])
    ref = fslimage.Image(ref, xform=xform)

    overlayList.extend([ref, mesh])

    displayCtx.displaySpace = ref

    mopts = displayCtx.getOpts(mesh)
    ropts = displayCtx.getOpts(ref)

    mopts.refImage = ref

    # world display mesh
    spaces = ['world', 'display', 'mesh', 'voxel']

    (xlo, ylo, zlo), (xhi, yhi, zhi) = mesh.bounds

    coords = {
        'mesh': np.array([xhi - xlo, yhi - ylo, zhi - zlo]),
        'world': np.array([3.92563438, 27.8010308, 34.60089011]),
        'display': np.array([23.10099983, 32.8390007, 23.02000046]),
        'voxel': np.array([15.40066655, 21.89266713, 15.34666697]),
    }

    for from_, to in it.permutations(coords, 2):
        exp = coords[to]
        got = mopts.transformCoords(coords[from_], from_, to)
        assert np.all(np.isclose(got, exp))
コード例 #9
0
def _test_image_indexed_read4D(threaded):

    with tests.testdir() as testdir:

        filename = op.join(testdir, 'image.nii.gz')

        # Data range grows with volume
        nvols = 50
        data = np.zeros((50, 50, 50, nvols))
        for vol in range(nvols):
            data[..., vol] = vol

        fslimage.Image(data).save(filename)

        img = fslimage.Image(filename,
                             loadData=False,
                             calcRange=False,
                             indexed=True,
                             threaded=threaded)

        # Test reading slice through
        # 4D (e.g. voxel time course)
        #
        # n.b. This is SUPER SLOW!!
        voxels = tests.random_voxels((50, 50, 50), 5)
        for i, xyz in enumerate(voxels):

            x, y, z = [int(v) for v in xyz]
            data = img[x, y, z, :]

            if threaded:
                img.getImageWrapper().getTaskThread().waitUntilIdle()

            assert np.all(data == np.arange(nvols))
コード例 #10
0
def test_applyDeformation_worldAligned():
    refv2w   = affine.scaleOffsetXform([1, 1, 1], [10,   10,   10])
    fieldv2w = affine.scaleOffsetXform([2, 2, 2], [10.5, 10.5, 10.5])
    src2ref  = refv2w
    ref2src  = affine.invert(src2ref)

    srcdata = np.random.randint(1, 65536, (10, 10, 10))

    src   = fslimage.Image(srcdata)
    ref   = fslimage.Image(srcdata, xform=src2ref)
    field = _affine_field(src, ref, ref2src, 'world', 'world',
                          shape=(5, 5, 5), fv2w=fieldv2w)

    field = nonlinear.DeformationField(
        nonlinear.convertDeformationType(field, 'absolute'),
        header=field.header,
        src=src,
        ref=ref,
        srcSpace='world',
        refSpace='world',
        defType='absolute')

    expect, xf = resample.resampleToReference(
        src, ref, matrix=src2ref, order=1, mode='constant', cval=0)
    result = nonlinear.applyDeformation(
        src, field, order=1, mode='constant', cval=0)

    expect = expect[1:-1, 1:-1, 1:-1]
    result = result[1:-1, 1:-1, 1:-1]

    assert np.all(np.isclose(expect, result))
コード例 #11
0
def test_readFnirt_defType_intent():
    src = op.join(datadir, 'src.nii.gz')
    ref = op.join(datadir, 'ref.nii.gz')
    coef = op.join(datadir, 'coefficientfield.nii.gz')
    disp = op.join(datadir, 'displacementfield.nii.gz')

    src = fslimage.Image(src)
    ref = fslimage.Image(ref)

    field = fnirt.readFnirt(disp, src, ref, defType='absolute')
    assert field.deformationType == 'absolute'
    field = fnirt.readFnirt(disp, src, ref, defType='relative')
    assert field.deformationType == 'relative'

    img = nib.load(coef)
    img.header['intent_code'] = 0
    with tempdir.tempdir():
        img.to_filename('field.nii.gz')

        with pytest.raises(ValueError):
            fnirt.readFnirt('field', src, ref)

        field = fnirt.readFnirt('field',
                                src,
                                ref,
                                intent=constants.FSL_CUBIC_SPLINE_COEFFICIENTS)
        assert isinstance(field, nonlinear.CoefficientField)

        field = fnirt.readFnirt('field',
                                src,
                                ref,
                                intent=constants.FSL_FNIRT_DISPLACEMENT_FIELD)
        assert isinstance(field, nonlinear.DeformationField)
コード例 #12
0
def makergb(infile, nchannels):

    img = fslimage.Image(infile)
    indata = img.data[..., :nchannels]

    if nchannels == 3:
        dtype = np.dtype([('R', 'uint8'), ('G', 'uint8'), ('B', 'uint8')])
    else:
        dtype = np.dtype([('R', 'uint8'), ('G', 'uint8'), ('B', 'uint8'),
                          ('A', 'uint8')])

    outdata = np.zeros(indata.shape[:3], dtype=dtype)

    for cn, ci in zip('RGBA', range(nchannels)):
        cd = indata[..., ci].astype(np.float32)
        lo, hi = cd.min(), cd.max()
        cd = (ci + 1) * 255 * (cd - lo) / (hi - lo)
        outdata[cn] = np.round(cd).astype(np.uint8)

    img = fslimage.Image(outdata, header=img.header)
    name = fslimage.removeExt(op.basename(infile))
    name = '{}_makergb_{}'.format(name, nchannels)

    img.save(name)

    return name
コード例 #13
0
def test_loadMetadata():
    with tempdir():
        make_image('image.nii.gz')

        meta = {'a': 1, 'b': 2}
        with open('image.json', 'wt') as f:
            json.dump(meta, f)

        img = fslimage.Image('image.nii.gz')
        gotmeta = fslimage.loadMetadata(img)

        assert gotmeta == meta

    with tempdir():
        imgfile = op.join('data', 'sub-01', 'anat', 'sub-01_T1w.nii.gz')
        metafile = op.join('data', 'T1w.json')

        os.makedirs(op.dirname(imgfile))
        make_image(imgfile)

        with open(op.join('data', 'dataset_description.json'), 'wt') as f:
            pass

        meta = {'a': 1, 'b': 2}
        with open(metafile, 'wt') as f:
            json.dump(meta, f)

        img = fslimage.Image(imgfile)
        gotmeta = fslimage.loadMetadata(img)

        assert gotmeta == meta
コード例 #14
0
def test_resampleToPixdims():

    img = fslimage.Image(make_random_image(dims=(10, 10, 10)))
    imglo, imghi = affine.axisBounds(img.shape, img.voxToWorldMat)
    oldpix = np.array(img.pixdim, dtype=float)
    oldshape = np.array(img.shape, dtype=float)

    for i, origin in it.product(range(25), ('centre', 'corner')):

        # random pixdims in the range 0.1 - 5.0
        newpix = 0.1 + 4.9 * np.random.random(3)
        expshape = np.round(oldshape * (oldpix / newpix))

        res = resample.resampleToPixdims(img, newpix, origin=origin)
        res = fslimage.Image(res[0], xform=res[1])
        reslo, reshi = affine.axisBounds(res.shape, res.voxToWorldMat)
        resfov = reshi - reslo
        expfov = newpix * res.shape

        assert np.all(np.isclose(res.shape, expshape))
        assert np.all(np.isclose(res.pixdim, newpix))
        assert np.all(np.isclose(resfov, expfov, rtol=1e-2, atol=1e-2))

        if origin == 'corner':
            assert np.all(np.isclose(imglo, reslo))
            assert np.all(
                np.isclose(reshi, reslo + expfov, rtol=1e-2, atol=1e-2))
コード例 #15
0
def test_readFnirt():

    src = op.join(datadir, 'src')
    ref = op.join(datadir, 'ref')
    coef = op.join(datadir, 'coefficientfield')
    disp = op.join(datadir, 'displacementfield')

    src = fslimage.Image(src)
    ref = fslimage.Image(ref)
    coef = fnirt.readFnirt(coef, src, ref)
    disp = fnirt.readFnirt(disp, src, ref)

    with pytest.raises(ValueError):
        fnirt.readFnirt(src, src, ref)

    assert isinstance(coef, nonlinear.CoefficientField)
    assert isinstance(disp, nonlinear.DeformationField)

    assert coef.src.sameSpace(src)
    assert coef.ref.sameSpace(ref)
    assert disp.src.sameSpace(src)
    assert disp.ref.sameSpace(ref)
    assert coef.srcSpace == 'fsl'
    assert coef.refSpace == 'fsl'
    assert disp.srcSpace == 'fsl'
    assert disp.refSpace == 'fsl'
コード例 #16
0
def test_coefficientFieldToDeformationField():

    nldir = op.join(datadir, 'nonlinear')
    src = op.join(nldir, 'src.nii.gz')
    ref = op.join(nldir, 'ref.nii.gz')
    cf = op.join(nldir, 'coefficientfield.nii.gz')
    df = op.join(nldir, 'displacementfield.nii.gz')
    dfnp = op.join(nldir, 'displacementfield_no_premat.nii.gz')

    src = fslimage.Image(src)
    ref = fslimage.Image(ref)
    cf = fnirt.readFnirt(cf, src, ref)
    rdf = fnirt.readFnirt(df, src, ref)
    rdfnp = fnirt.readFnirt(dfnp, src, ref)
    adf = nonlinear.convertDeformationType(rdf)
    adfnp = nonlinear.convertDeformationType(rdfnp)

    rcnv = nonlinear.coefficientFieldToDeformationField(cf)
    acnv = nonlinear.coefficientFieldToDeformationField(cf, defType='absolute')
    acnvnp = nonlinear.coefficientFieldToDeformationField(cf,
                                                          defType='absolute',
                                                          premat=False)
    rcnvnp = nonlinear.coefficientFieldToDeformationField(cf, premat=False)

    tol = dict(atol=1e-5, rtol=1e-5)
    assert np.all(np.isclose(rcnv.data, rdf.data, **tol))
    assert np.all(np.isclose(acnv.data, adf.data, **tol))
    assert np.all(np.isclose(rcnvnp.data, rdfnp.data, **tol))
    assert np.all(np.isclose(acnvnp.data, adfnp.data, **tol))
コード例 #17
0
def _test_group(frame, overlayList, displayCtx):

    # Currently there is always only one group
    group = displayCtx.overlayGroups[0]
    img1  = fslimage.Image(op.join(datadir, '3d'))
    img2  = fslimage.Image(op.join(datadir, '4d'))

    # all new images should be
    # added to the overlay group
    overlayList.append(img1)
    assert img1 in group

    # Overlays should be automatically
    # removed from the group
    del overlayList[:]
    assert len(group) == 0

    overlayList.append(img1)
    overlayList.append(img2)
    assert img1 in group
    assert img2 in group

    del overlayList[0]
    assert img1 not in group
    assert img2     in group
    del overlayList[0]
    assert img1 not in group
    assert img2 not in group
コード例 #18
0
def test_coefficientField_transform_altref():

    # test coordinates (manually determined).
    # original ref image is 2mm isotropic,
    # resampled is 1mm. Each tuple contains:
    #
    # (src, ref2mm, ref1mm)
    coords = [((18.414, 26.579, 25.599), (11, 19, 11), (22, 38, 22)),
              ((14.727, 22.480, 20.340), (8, 17, 8), (16, 34, 16)),
              ((19.932, 75.616, 27.747), (11, 45, 5), (22, 90, 10))]

    nldir = op.join(datadir, 'nonlinear')
    src = op.join(nldir, 'src.nii.gz')
    ref = op.join(nldir, 'ref.nii.gz')
    cf = op.join(nldir, 'coefficientfield.nii.gz')

    src = fslimage.Image(src)
    ref2mm = fslimage.Image(ref)
    ref1mm = ref2mm.adjust((1, 1, 1))
    cfref2mm = fnirt.readFnirt(cf, src, ref2mm)
    cfref1mm = fnirt.readFnirt(cf, src, ref1mm)

    for srcc, ref2mmc, ref1mmc in coords:
        ref2mmc = cfref2mm.transform(ref2mmc, 'voxel', 'voxel')
        ref1mmc = cfref1mm.transform(ref1mmc, 'voxel', 'voxel')

        assert np.all(np.isclose(ref2mmc, srcc, 1e-4))
        assert np.all(np.isclose(ref1mmc, srcc, 1e-4))
コード例 #19
0
def test_prepareMask():

    reg = atlases.registry
    reg.rescanAtlases()

    probatlas    = reg.loadAtlas('harvardoxford-cortical',
                                 indexed=True, loadData=False, calcRange=False)
    probsumatlas = reg.loadAtlas('harvardoxford-cortical', loadSummary=True)
    lblatlas     = reg.loadAtlas('talairach')

    for atlas in [probatlas, probsumatlas, lblatlas]:

        ashape        = list(atlas.shape[:3])
        m2shape       = [s * 1.5 for s in ashape]

        goodmask1     = fslimage.Image(
            np.array(np.random.random(ashape), dtype=np.float32),
            xform=atlas.voxToWorldMat)

        goodmask2, xf = goodmask1.resample(m2shape)
        goodmask2     = fslimage.Image(goodmask2, xform=xf)

        wrongdims     = fslimage.Image(
            np.random.random(list(ashape) + [2]))
        wrongspace    = fslimage.Image(
            np.random.random((20, 20, 20)),
            xform=transform.concat(atlas.voxToWorldMat, np.diag([2, 2, 2, 1])))

        with pytest.raises(atlases.MaskError):
            atlas.prepareMask(wrongdims)
        with pytest.raises(atlases.MaskError):
            atlas.prepareMask(wrongspace)

        assert list(atlas.prepareMask(goodmask1).shape) == ashape
        assert list(atlas.prepareMask(goodmask2).shape) == ashape
コード例 #20
0
def test_CoefficientField_displacements():

    nldir = op.join(datadir, 'nonlinear')
    src = op.join(nldir, 'src.nii.gz')
    ref = op.join(nldir, 'ref.nii.gz')
    cf = op.join(nldir, 'coefficientfield.nii.gz')
    df = op.join(nldir, 'displacementfield_no_premat.nii.gz')

    src = fslimage.Image(src)
    ref = fslimage.Image(ref)
    cf = fnirt.readFnirt(cf, src, ref)
    df = fnirt.readFnirt(df, src, ref)

    ix, iy, iz = ref.shape[:3]
    x, y, z = np.meshgrid(np.arange(ix),
                          np.arange(iy),
                          np.arange(iz),
                          indexing='ij')
    x = x.flatten()
    y = y.flatten()
    z = z.flatten()
    xyz = np.vstack((x, y, z)).T

    disps = cf.displacements(xyz)
    disps = disps.reshape(df.shape)

    tol = dict(atol=1e-5, rtol=1e-5)
    assert np.all(np.isclose(disps, df.data, **tol))
コード例 #21
0
def gen_indices(infile):
    basename = fslimage.removeExt(op.basename(infile))
    outfile = '{}_indices.nii.gz'.format(basename)
    img = fslimage.Image(infile, loadData=False)
    shape = img.shape
    data = np.arange(np.prod(shape)).reshape(shape)

    fslimage.Image(data, header=img.header).save(outfile)

    return outfile
コード例 #22
0
def test_CoefficientField_transform():
    nldir = op.join(datadir, 'nonlinear')
    src = op.join(nldir, 'src.nii.gz')
    ref = op.join(nldir, 'ref.nii.gz')
    cf = op.join(nldir, 'coefficientfield.nii.gz')
    df = op.join(nldir, 'displacementfield.nii.gz')
    dfnp = op.join(nldir, 'displacementfield_no_premat.nii.gz')

    src = fslimage.Image(src)
    ref = fslimage.Image(ref)
    cf = fnirt.readFnirt(cf, src, ref)
    df = fnirt.readFnirt(df, src, ref)
    dfnp = fnirt.readFnirt(dfnp, src, ref)

    spaces = ['fsl', 'voxel', 'world']
    spaces = list(it.combinations_with_replacement(spaces, 2))
    spaces = spaces + [(r, s) for s, r in spaces]
    spaces = list(set(spaces))

    rx, ry, rz = np.meshgrid(np.arange(ref.shape[0]),
                             np.arange(ref.shape[1]),
                             np.arange(ref.shape[2]),
                             indexing='ij')
    rvoxels = np.vstack((rx.flatten(), ry.flatten(), rz.flatten())).T

    refcoords = {
        'voxel': rvoxels,
        'fsl': affine.transform(rvoxels, ref.getAffine('voxel', 'fsl')),
        'world': affine.transform(rvoxels, ref.getAffine('voxel', 'world'))
    }

    srccoords = refcoords['fsl'] + df.data.reshape(-1, 3)
    srccoords = {
        'voxel': affine.transform(srccoords, src.getAffine('fsl', 'voxel')),
        'fsl': srccoords,
        'world': affine.transform(srccoords, src.getAffine('fsl', 'world'))
    }

    srccoordsnp = refcoords['fsl'] + dfnp.data.reshape(-1, 3)
    srccoordsnp = {
        'voxel': affine.transform(srccoordsnp, src.getAffine('fsl', 'voxel')),
        'fsl': srccoordsnp,
        'world': affine.transform(srccoordsnp, src.getAffine('fsl', 'world'))
    }

    tol = dict(atol=1e-5, rtol=1e-5)
    for srcspace, refspace in spaces:
        got = cf.transform(refcoords[refspace], refspace, srcspace)
        gotnp = cf.transform(refcoords[refspace],
                             refspace,
                             srcspace,
                             premat=False)
        assert np.all(np.isclose(got, srccoords[srcspace], **tol))
        assert np.all(np.isclose(gotnp, srccoordsnp[srcspace], **tol))
コード例 #23
0
def binarise(infile, low, high, scale=1):

    basename = fslimage.removeExt(op.basename(infile))
    outfile = '{}_binarised_{}_{}_{}.nii.gz'.format(basename, low, high, scale)
    img = fslimage.Image(infile)
    data = img[:]
    binned = ((data > low) & (data < high)).astype(np.uint8) * scale

    fslimage.Image(binned, header=img.header).save(outfile)

    return outfile
コード例 #24
0
def _test_copyDisplayProperties(panel, overlayList, displayCtx):
    displayCtx = panel.displayCtx
    img1 = fslimage.Image(np.random.randint(1, 255, (20, 20, 20)))
    img2 = fslimage.Image(np.random.randint(1, 255, (20, 20, 20)))

    overlayList.extend((img1, img2))

    realYield(50)
    disp1 = displayCtx.getDisplay(img1)
    disp2 = displayCtx.getDisplay(img2)
    opts1 = displayCtx.getOpts(img1)
    opts2 = displayCtx.getOpts(img2)

    disp1.name = 'hurdi hur'
    disp1.brightness = 75
    disp1.contrast = 25
    opts1.cmap = 'blue-lightblue'

    realYield(50)
    copyoverlay.copyDisplayProperties(displayCtx, img1, img2)
    realYield(50)

    assert disp2.name == 'hurdi hur'
    assert np.isclose(disp2.brightness, 75)
    assert np.isclose(disp2.contrast, 25)
    assert opts2.cmap.name == 'blue-lightblue'

    disp1.name = 'wuzzle wazzle'
    opts1.gamma = 0.75
    opts1.cmap = 'red-yellow'

    copyoverlay.copyDisplayProperties(displayCtx,
                                      img1,
                                      img2,
                                      displayExclude=['name'],
                                      optExclude=['cmap'])

    assert disp2.name == 'hurdi hur'
    assert np.isclose(opts2.gamma, 0.75)
    assert opts2.cmap.name == 'blue-lightblue'

    disp1.name = 'walla walla'
    opts1.gamma = 0.6
    opts1.cmap = 'hot'

    copyoverlay.copyDisplayProperties(displayCtx,
                                      img1,
                                      img2,
                                      displayArgs={'name': 'herp derp'},
                                      optArgs={'gamma': 0.2})

    assert disp2.name == 'herp derp'
    assert np.isclose(opts2.gamma, 0.2)
    assert opts2.cmap.name == 'hot'
コード例 #25
0
ファイル: __init__.py プロジェクト: sanjayankur31/fsleyes
def roi(fname, roi):
    base    = fslimage.removeExt(fname)
    outfile = '{}_roi_{}_{}_{}_{}_{}_{}'.format(base, *roi)

    img = fslimage.Image(fname)
    xs, xe, ys, ye, zs, ze = roi
    data = img[xs:xe, ys:ye, zs:ze, ...]
    img = fslimage.Image(data, header=img.header)

    img.save(outfile)

    return outfile
コード例 #26
0
def test_applyDeformation_premat():

    src2ref = affine.compose(
        np.random.randint(2, 5, 3),
        np.random.randint(1, 10, 3),
        [0, 0, 0])
    ref2src = affine.invert(src2ref)

    srcdata = np.random.randint(1, 65536, (10, 10, 10))
    refdata = np.random.randint(1, 65536, (10, 10, 10))

    src   = fslimage.Image(srcdata)
    ref   = fslimage.Image(refdata, xform=src2ref)
    field = _affine_field(src, ref, ref2src, 'world', 'world')

    # First try a down-sampled version
    # of the original source image
    altsrc, xf = resample.resample(src, (5, 5, 5), origin='corner')
    altsrc     = fslimage.Image(altsrc, xform=xf, header=src.header)
    expect, xf = resample.resampleToReference(
        altsrc, ref, matrix=src2ref, order=1, mode='nearest')
    premat = affine.concat(src   .getAffine('world', 'voxel'),
                           altsrc.getAffine('voxel', 'world'))
    result = nonlinear.applyDeformation(
        altsrc, field, order=1, mode='nearest', premat=premat)
    assert np.all(np.isclose(expect, result))

    # Now try a down-sampled ROI
    # of the original source image
    altsrc     = roi.roi(src, [(2, 9), (2, 9), (2, 9)])
    altsrc, xf = resample.resample(altsrc, (4, 4, 4))
    altsrc     = fslimage.Image(altsrc, xform=xf, header=src.header)
    expect, xf = resample.resampleToReference(
        altsrc, ref, matrix=src2ref, order=1, mode='nearest')
    premat = affine.concat(src   .getAffine('world', 'voxel'),
                           altsrc.getAffine('voxel', 'world'))
    result = nonlinear.applyDeformation(
        altsrc, field, order=1, mode='nearest', premat=premat)
    assert np.all(np.isclose(expect, result))

    # down-sampled and offset ROI
    # of the original source image
    altsrc     = roi.roi(src, [(-5, 8), (-5, 8), (-5, 8)])
    altsrc, xf = resample.resample(altsrc, (6, 6, 6))
    altsrc     = fslimage.Image(altsrc, xform=xf, header=src.header)
    expect, xf = resample.resampleToReference(
        altsrc, ref, matrix=src2ref, order=1, mode='nearest')
    premat = affine.concat(src   .getAffine('world', 'voxel'),
                           altsrc.getAffine('voxel', 'world'))
    result = nonlinear.applyDeformation(
        altsrc, field, order=1, mode='nearest', premat=premat)
    assert np.all(np.isclose(expect, result))
コード例 #27
0
def _test_CopyOverlayAction(panel, overlayList, displayCtx):

    img3d = fslimage.Image(np.random.randint(1, 255, (20, 20, 20)))
    img4d = fslimage.Image(np.random.randint(1, 255, (20, 20, 20, 20)))
    overlayList.extend((img3d, img4d))

    class CheckBoxMessageDialog(object):
        ShowModal_return = wx.ID_YES
        CheckBoxState_return = [False, False, False]

        def __init__(self, *a, **kwa):
            pass

        def ShowModal(self):
            return CheckBoxMessageDialog.ShowModal_return

        def CheckBoxState(self, cb):
            return CheckBoxMessageDialog.CheckBoxState_return[cb]

    with mock.patch('fsleyes_widgets.dialog.CheckBoxMessageDialog',
                    CheckBoxMessageDialog):

        act = copyoverlay.CopyOverlayAction(overlayList, displayCtx,
                                            panel.frame)

        CheckBoxMessageDialog.ShowModal_return = wx.ID_CANCEL
        act()
        assert len(overlayList) == 2

        displayCtx.selectOverlay(img3d)
        CheckBoxMessageDialog.ShowModal_return = wx.ID_YES
        act()
        assert len(overlayList) == 3
        print(overlayList)
        copy = overlayList[1]
        assert np.all(copy[:] == img3d[:])
        overlayList.remove(copy)

        displayCtx.selectOverlay(img4d)
        act()
        assert len(overlayList) == 3
        copy = overlayList[2]
        assert np.all(copy[:] == img4d[..., 0])
        overlayList.remove(copy)

        CheckBoxMessageDialog.CheckBoxState_return = [False, False, True]
        displayCtx.selectOverlay(img4d)
        act()
        assert len(overlayList) == 3
        copy = overlayList[2]
        assert np.all(copy[:] == img4d[:])
        overlayList.remove(copy)
コード例 #28
0
def oblique(infile):

    basename = fslimage.removeExt(op.basename(infile))
    outfile = '{}_oblique.nii.gz'.format(basename)
    img = fslimage.Image(infile)
    xform = img.getAffine('voxel', 'world')
    rot = affine.compose([1, 1, 1], [0, 0, 0], [0, 0, 1])
    xform = affine.concat(rot, xform)
    img = fslimage.Image(img.data, xform=xform)

    img.save(outfile)

    return outfile
コード例 #29
0
def _test_image_indexed(threaded):

    with tests.testdir() as testdir:

        filename = op.join(testdir, 'image.nii.gz')

        # Data range grows with volume
        data  = np.zeros((50, 50, 50, 50))
        for vol in range(data.shape[-1]):
            data[..., vol] = vol

        fslimage.Image(data).save(filename)

        img = fslimage.Image(
            filename,
            loadData=False,
            calcRange=False,
            threaded=threaded)

        # First iteration through the image
        start1 = time.time()
        for vol in range(data.shape[-1]):

            img[..., vol]

            if threaded:
                img.getImageWrapper().getTaskThread().waitUntilIdle()

            assert img.dataRange == (0, vol)
        end1 = time.time()

        # Double check that indexed_gzip is
        # being used (the internal _opener
        # attribute is not created until
        # after the first data access)
        try:
            import indexed_gzip as igzip
            assert isinstance(img.nibImage.dataobj._opener.fobj,
                              igzip.IndexedGzipFile)
        except ImportError:
            pass

        # Second iteration through
        start2 = time.time()
        for vol in range(data.shape[-1]):
            img[..., vol]
        end2 = time.time()

        # Second iteration should be much faster!
        assert (end1 - start1) > (end2 - start2)
コード例 #30
0
def _test_screenshot(panel, overlayList, displayCtx, stype, imgfile):

    import matplotlib.image as mplimg
    import fsleyes.actions.screenshot as screenshot
    import fsleyes.views.orthopanel as orthopanel

    if isinstance(panel, orthopanel.OrthoPanel):
        panel.sceneOpts.showCursor = False
        panel.sceneOpts.showLabels = False

    img = fslimage.Image(op.join(datadir, imgfile))

    overlayList.append(img)

    with tempdir():

        fname = 'test_screenshot_{}.png'.format(stype)

        realYield(100)
        idle.idle(screenshot.screenshot, panel, fname)
        realYield()

        bfname = op.join(datadir, 'test_screenshot_{}.png'.format(stype))
        screenshot = mplimg.imread(fname)
        benchmark = mplimg.imread(bfname)

        result, diff = compare_images(screenshot, benchmark, 50)

        print('Comparing {} with {}: {}'.format(fname, bfname, diff))

        assert result