def SetScale(scale):
        '''Scale Management for Multiscale'''
        scaleManager.set(scale)
        resampler.setScaleLevel(scaleManager)
        curGrid = scaleManager.getCurGrid()
        curGrid.spacing().z = 1  # Because only 2D

        print 'Inside setScale(). Current grid is ', curGrid

        if scaleManager.isLastScale():
            print 'Inside setScale(): **Last Scale**'
        if scaleManager.isFirstScale():
            print 'Inside setScale(): **First Scale**'

        scratchISrc.setGrid(curGrid)
        scratchITar.setGrid(curGrid)
        scratchI.setGrid(curGrid)
        compF.setGrid(curGrid)
        idConf.study.I0 = ca.Image3D(curGrid, memT)
        idConf.study.I1 = ca.Image3D(curGrid, memT)

        if scaleManager.isLastScale():
            s = config.sigBlur[scaleList.index(sc)]
            r = config.kerBlur[scaleList.index(sc)]
            gausFilt.updateParams(I_tar.size(), ca.Vec3Df(r, r, r),
                                  ca.Vec3Di(s, s, s))
            gausFilt.filter(scratchITar, I_tar, temp)
            gausFilt.filter(scratchI, I_src, temp)

# ca.Copy(scratchI, I_src)
# ca.Copy(scratchITar, I_tar)

        else:
            s = config.sigBlur[scaleList.index(sc)]
            r = config.kerBlur[scaleList.index(sc)]
            gausFilt.updateParams(I_tar.size(), ca.Vec3Df(r, r, r),
                                  ca.Vec3Di(s, s, s))
            gausFilt.filter(I_tar_blur, I_tar, temp)
            gausFilt.filter(I_src_blur, I_src, temp)
            resampler.downsampleImage(scratchI, I_src_blur)
            resampler.downsampleImage(scratchITar, I_tar_blur)

        if scaleManager.isFirstScale():
            scratchF.setGrid(curGrid)
            scratchITar.setGrid(curGrid)
            ca.SetToIdentity(scratchF)
            ca.ApplyH(scratchISrc, scratchI, scratchF)

        else:
            compF.setGrid(scratchF.grid())
            ca.ComposeHH(compF, scratchF, h)
            resampler.updateHField(scratchF)
            resampler.updateHField(compF)
            ca.Copy(scratchF, compF)
            ca.ApplyH(scratchISrc, scratchI, compF)
Ejemplo n.º 2
0
 def test_SplatAdjoint(self, disp=False):
     hI = common.RandImage(self.sz,
                           nSig=1.0,
                           gSig=0.0,
                           mType=ca.MEM_HOST,
                           sp=self.imSp)
     hJ = common.RandImage(self.sz,
                           nSig=1.0,
                           gSig=0.0,
                           mType=ca.MEM_HOST,
                           sp=self.imSp)
     hPhi = common.RandField(self.sz,
                             nSig=5.0,
                             gSig=4.0,
                             mType=ca.MEM_HOST,
                             sp=self.imSp)
     tmp = ca.Image3D(self.grid, ca.MEM_HOST)
     # compute < I(Phi(x)), J(x) >
     ca.ApplyH(tmp, hI, hPhi)
     phiIdotJ = ca.Dot(tmp, hJ)
     # compute < I(y), |DPhi^{-1}(y)| J(Phi^{-1}(y)) >
     ca.Splat(tmp, hPhi, hJ)
     IdotphiJ = ca.Dot(tmp, hI)
     #print "a=%f b=%f" % (phiIdotJ, IdotphiJ)
     self.assertLess(abs(phiIdotJ - IdotphiJ), 2e-6)
Ejemplo n.º 3
0
def geodesic_shooting_diffOp(moving, target, m0, steps, mType, config):
	grid = moving.grid()
	m0.setGrid(grid)
	ca.ThreadMemoryManager.init(grid, mType, 1)
	if mType == ca.MEM_HOST:
		diffOp = ca.FluidKernelFFTCPU()
	else:
		diffOp = ca.FluidKernelFFTGPU()
	diffOp.setAlpha(config['deformation_params']['diffOpParams'][0])
	diffOp.setBeta(config['deformation_params']['diffOpParams'][1])
	diffOp.setGamma(config['deformation_params']['diffOpParams'][2])
	diffOp.setGrid(grid)

	g = ca.Field3D(grid, mType)
	ginv = ca.Field3D(grid, mType)
	mt = ca.Field3D(grid, mType)
	It = ca.Image3D(grid, mType)
	It_inv = ca.Image3D(grid, mType)

	if (steps <= 0):
		time_steps = config['deformation_params']['timeSteps'];
	else:
		time_steps = steps;

	t = [x*1./time_steps for x in range(time_steps+1)]
	checkpointinds = range(1,len(t))
	checkpointstates =  [(ca.Field3D(grid,mType),ca.Field3D(grid,mType)) for idx in checkpointinds]

	scratchV1 = ca.Field3D(grid,mType)
	scratchV2 = ca.Field3D(grid,mType)
	scratchV3 = ca.Field3D(grid,mType)    

	CAvmCommon.IntegrateGeodesic(m0,t,diffOp, mt, g, ginv,\
								 scratchV1,scratchV2,scratchV3,\
                                 keepstates=checkpointstates,keepinds=checkpointinds,
                                 Ninv=config['deformation_params']['NIterForInverse'], integMethod = config['deformation_params']['integMethod'])
	ca.ApplyH(It,moving,ginv)
	ca.ApplyH(It_inv,target,g)

	output={'I1':It, 'I1_inv': It_inv, "phiinv":ginv}
	return output
Ejemplo n.º 4
0
def DefSeriesIter(I, V, t, func, args):
    grid = I.grid()
    mType = I.memType()
    tlen = len(t)
    h = core.Field3D(grid, mType)
    IDef = core.Image3D(grid, mType)
    core.SetToIdentity(h)
    scratchV1 = core.Field3D(grid, mType)
    scratchV2 = core.Field3D(grid, mType)
    rtnarr = []
    for tidx in range(tlen):
        curt = t[tidx]
        h = common.ComposeDef(V, curt, inverse=True,
                              asVField=False,
                              scratchV1=scratchV1,
                              scratchV2=scratchV2)
        core.ApplyH(IDef, I, h)
        r = func(IDef, curt, *args)
        rtnarr.append(r)
    return rtnarr
Ejemplo n.º 5
0
def MatchingGradient(p):
    # shoot the geodesic forward    
    CAvmCommon.IntegrateGeodesic(p.m0,p.t,p.diffOp, \
                      p.m, p.g, p.ginv,\
                      p.scratchV1, p.scratchV2,p. scratchV3,\
                      p.checkpointstates, p.checkpointinds,\
                      Ninv=p.nInv, integMethod = p.integMethod, RK4=p.scratchV4,scratchG=p.scratchV5)


    endidx = p.checkpointinds.index(len(p.t)-1)
    # compute residual image
    ca.ApplyH(p.residualIm,p.I0,p.ginv)
    ca.Sub_I(p.residualIm, p.I1)
    # while we have residual, save the image energy
    IEnergy = ca.Sum2(p.residualIm)/(2*p.sigma*p.sigma*float(p.I0.nVox()))
    
    ca.DivC_I(p.residualIm, p.sigma*p.sigma) # gradient at measurement
    
    # integrate backward
    CAvmCommon.IntegrateAdjoints(p.Iadj,p.madj,\
                      p.I,p.m,p.Iadjtmp, p.madjtmp,p.scratchV1,\
                      p.scratchV2,p.scratchV3,\
                      p.I0,p.m0,\
                      p.t, p.checkpointstates, p.checkpointinds,\
                      [p.residualIm], [endidx],\
                      p.diffOp,
                      p.integMethod, p.nInv, \
                      scratchV3=p.scratchV7, scratchV4=p.g,scratchV5=p.ginv,scratchV6=p.scratchV8, scratchV7=p.scratchV9, \
                      scratchV8=p.scratchV10,scratchV9=p.scratchV11,\
                      RK4=p.scratchV4, scratchG=p.scratchV5, scratchGinv=p.scratchV6)
                      
    
    # compute gradient
    ca.Copy(p.scratchV1, p.m0)
    p.diffOp.applyInverseOperator(p.scratchV1)
    # while we have velocity, save the vector energy
    VEnergy = 0.5*ca.Dot(p.m0,p.scratchV1)/float(p.I0.nVox())

    ca.Sub_I(p.scratchV1, p.madj)
    #p.diffOp.applyOperator(p.scratchV1)
    return (p.scratchV1, VEnergy, IEnergy)
def MatchingImageMomentaComputeEnergy(geodesicState, m0, J1, n1):
    vecEnergy = 0.0
    imageMatchEnergy = 0.0
    momentaMatchEnergy = 0.0

    grid = geodesicState.J0.grid()
    mType = geodesicState.J0.memType()

    imdiff = ca.ManagedImage3D(grid, mType)
    vecdiff = ca.ManagedField3D(grid, mType)

    # image match energy
    ca.ApplyH(imdiff, geodesicState.J0, geodesicState.rhoinv)
    ca.Sub_I(imdiff, J1)
    imageMatchEnergy = 0.5 * ca.Sum2(imdiff) / (
        float(geodesicState.p0.nVox()) * geodesicState.Sigma *
        geodesicState.Sigma * geodesicState.SigmaIntercept *
        geodesicState.SigmaIntercept)  # save for use in intercept energy term

    # momenta match energy
    ca.CoAd(geodesicState.p, geodesicState.rhoinv, m0)
    ca.Sub_I(geodesicState.p, n1)
    ca.Copy(vecdiff, geodesicState.p)  # save for use in slope energy term
    geodesicState.diffOp.applyInverseOperator(geodesicState.p)
    momentaMatchEnergy = ca.Dot(vecdiff, geodesicState.p) / (
        float(geodesicState.p0.nVox()) * geodesicState.SigmaSlope *
        geodesicState.SigmaSlope)

    # vector energy. p is used as scratch variable
    ca.Copy(geodesicState.p, geodesicState.p0)
    geodesicState.diffOp.applyInverseOperator(geodesicState.p)
    vecEnergy = 0.5 * ca.Dot(geodesicState.p0, geodesicState.p) / (
        float(geodesicState.p0.nVox()) * geodesicState.SigmaIntercept *
        geodesicState.SigmaIntercept)

    return (vecEnergy, imageMatchEnergy, momentaMatchEnergy)
def MatchingImageMomentaWriteOuput(cf, geodesicState, EnergyHistory, m0, n1):
    grid = geodesicState.J0.grid()
    mType = geodesicState.J0.memType()

    # save momenta for the gedoesic
    common.SaveITKField(geodesicState.p0, cf.io.outputPrefix + "p0.mhd")

    # save matched momenta for the geodesic
    if cf.vectormomentum.matchImOnly:
        m0 = common.LoadITKField(cf.study.m, mType)

    ca.CoAd(geodesicState.p, geodesicState.rhoinv, m0)
    common.SaveITKField(geodesicState.p, cf.io.outputPrefix + "m1.mhd")

    # momenta match energy
    if cf.vectormomentum.matchImOnly:
        vecdiff = ca.ManagedField3D(grid, mType)
        ca.Sub_I(geodesicState.p, n1)
        ca.Copy(vecdiff, geodesicState.p)
        geodesicState.diffOp.applyInverseOperator(geodesicState.p)
        momentaMatchEnergy = ca.Dot(vecdiff, geodesicState.p) / (
            float(geodesicState.p0.nVox()) * geodesicState.SigmaSlope *
            geodesicState.SigmaSlope)
        # save energy
        energyFilename = cf.io.outputPrefix + "testMomentaMatchEnergy.csv"
        with open(energyFilename, 'w') as f:
            print >> f, momentaMatchEnergy

    # save matched image for the geodesic
    tempim = ca.ManagedImage3D(grid, mType)
    ca.ApplyH(tempim, geodesicState.J0, geodesicState.rhoinv)
    common.SaveITKImage(tempim, cf.io.outputPrefix + "I1.mhd")

    # save energy
    energyFilename = cf.io.outputPrefix + "energy.csv"
    MatchingImageMomentaWriteEnergyHistoryToFile(EnergyHistory, energyFilename)
def WarpGradient(p, t, Imsmts, cpinds, cpstates, msmtinds, gradAtMsmts):

    # shoot the geodesic forward
    CAvmCommon.IntegrateGeodesic(p.m0,t,p.diffOp, \
                                 p.m, p.g, p.ginv,\
                                 p.scratchV1, p.scratchV2,p. scratchV3,\
                                 cpstates, cpinds,\
                                 Ninv=p.nInv, integMethod = p.integMethod, RK4=p.scratchV4,scratchG=p.scratchV5)

    IEnergy = 0.0
    # compute residuals for each measurement timepoint along with computing energy
    for i in range(len(Imsmts)):
        if msmtinds[i] != -1:
            (g, ginv) = cpstates[msmtinds[i]]
            ca.ApplyH(gradAtMsmts[i], p.I0, ginv)
            ca.Sub_I(gradAtMsmts[i], Imsmts[i])
            # while we have residual, save the image energy
            IEnergy += ca.Sum2(
                gradAtMsmts[i]) / (2 * p.sigma * p.sigma * float(p.I0.nVox()))
            ca.DivC_I(gradAtMsmts[i],
                      p.sigma * p.sigma)  # gradient at measurement
        elif msmtinds[i] == -1:
            ca.Copy(gradAtMsmts[i], p.I0)
            ca.Sub_I(gradAtMsmts[i], Imsmts[i])
            # while we have residual, save the image energy
            IEnergy += ca.Sum2(
                gradAtMsmts[i]) / (2 * p.sigma * p.sigma * float(p.I0.nVox()))
            ca.DivC_I(gradAtMsmts[i],
                      p.sigma * p.sigma)  # gradient at measurement

    # integrate backward
    CAvmCommon.IntegrateAdjoints(p.Iadj,p.madj,\
                                 p.I,p.m,p.Iadjtmp, p.madjtmp,p.scratchV1,\
                                 p.scratchV2,p.scratchV3,\
                                 p.I0,p.m0,\
                                 t, cpstates, cpinds,\
                                 gradAtMsmts,msmtinds,\
                                 p.diffOp,\
                                 p.integMethod, p.nInv, \
                                 scratchV3=p.scratchV7, scratchV4=p.g,scratchV5=p.ginv,scratchV6=p.scratchV8, scratchV7=p.scratchV9, \
                                 scratchV8=p.scratchV10,scratchV9=p.scratchV11,\
                                 RK4=p.scratchV4, scratchG=p.scratchV5, scratchGinv=p.scratchV6,\
                                 scratchI = p.scratchI1)

    # compute gradient
    ca.Copy(p.scratchV1, p.m0)
    p.diffOp.applyInverseOperator(p.scratchV1)
    # while we have velocity, save the vector energy
    VEnergy = 0.5 * ca.Dot(p.m0, p.scratchV1) / float(p.I0.nVox())

    ca.Sub_I(p.scratchV1, p.madj)
    #p.diffOp.applyOperator(p.scratchV1)

    # compute closed from terms for image update
    # p.Iadjtmp and p.I will be used as scratch images
    scratchI = p.scratchI1  #reference assigned
    imOnes = p.I  #reference assigned
    ca.SetMem(imOnes, 1.0)
    ca.SetMem(p.sumSplatI, 0.0)
    ca.SetMem(p.sumJac, 0.0)
    #common.DebugHere()
    for i in range(len(Imsmts)):
        # TODO: check these indexings for cases when timepoint 0
        # is not checkpointed
        if msmtinds[i] != -1:
            (g, ginv) = cpstates[msmtinds[i]]
            CAvmCommon.SplatSafe(scratchI, ginv, Imsmts[i])
            ca.Add_I(p.sumSplatI, scratchI)
            CAvmCommon.SplatSafe(scratchI, ginv, imOnes)
            ca.Add_I(p.sumJac, scratchI)
        elif msmtinds[i] == -1:
            ca.Add_I(p.sumSplatI, Imsmts[i])
            ca.Add_I(p.sumJac, imOnes)
    return (p.scratchV1, p.sumJac, p.sumSplatI, VEnergy, IEnergy)
def MatchingImageMomentaPlots(cf,
                              geodesicState,
                              tDiscGeodesic,
                              EnergyHistory,
                              m0,
                              J1,
                              n1,
                              writeOutput=True):
    """
    Do some summary plots for MatchingImageMomenta
    """

    #ENERGY
    fig = plt.figure(1)
    plt.clf()
    fig.patch.set_facecolor('white')

    TE = [row[0] for row in EnergyHistory]
    VE = [row[1] for row in EnergyHistory]
    IE = [row[2] for row in EnergyHistory]
    ME = [row[3] for row in EnergyHistory]
    plt.subplot(2, 2, 1)
    plt.plot(TE)
    plt.title('Total Energy')
    plt.hold(False)
    plt.subplot(2, 2, 2)
    plt.plot(VE)
    plt.title('Vector Energy')
    plt.hold(False)
    plt.subplot(2, 2, 3)
    plt.plot(IE)
    plt.title('Image Match Energy')
    plt.hold(False)
    plt.subplot(2, 2, 4)
    plt.plot(ME)
    plt.title('Momenta Match Energy')
    plt.hold(False)
    plt.draw()
    plt.show()
    if cf.io.outputPrefix != None and writeOutput:
        plt.savefig(cf.io.outputPrefix + 'energy.pdf')

    # GEODESIC INITIAL CONDITIONS and RHO and RHO inv
    CAvmHGMCommon.HGMIntegrateGeodesic(geodesicState.p0, geodesicState.s,
                                       geodesicState.diffOp, geodesicState.p,
                                       geodesicState.rho, geodesicState.rhoinv,
                                       tDiscGeodesic, geodesicState.Ninv,
                                       geodesicState.integMethod)

    fig = plt.figure(2)
    plt.clf()
    fig.patch.set_facecolor('white')

    plt.subplot(2, 2, 1)
    display.DispImage(geodesicState.J0,
                      'J0',
                      newFig=False,
                      sliceIdx=cf.io.plotSlice)
    plt.subplot(2, 2, 2)
    ca.ApplyH(geodesicState.J, geodesicState.J0, geodesicState.rhoinv)
    display.DispImage(geodesicState.J,
                      'J1',
                      newFig=False,
                      sliceIdx=cf.io.plotSlice)

    plt.subplot(2, 2, 3)
    display.GridPlot(geodesicState.rhoinv,
                     every=cf.io.quiverEvery,
                     color='k',
                     sliceIdx=cf.io.plotSlice,
                     isVF=False)
    plt.axis('equal')
    plt.axis('off')
    plt.title('rho^{-1}')
    plt.subplot(2, 2, 4)
    display.GridPlot(geodesicState.rho,
                     every=cf.io.quiverEvery,
                     color='k',
                     sliceIdx=cf.io.plotSlice,
                     isVF=False)
    plt.axis('equal')
    plt.axis('off')
    plt.title('rho')
    if cf.io.outputPrefix != None and writeOutput:
        plt.savefig(cf.io.outputPrefix + 'def.pdf')

    # MATCHING DIFFERENCE IMAGES
    grid = geodesicState.J0.grid()
    mType = geodesicState.J0.memType()
    imdiff = ca.ManagedImage3D(grid, mType)

    # Image matching
    ca.Copy(imdiff, geodesicState.J)
    ca.Sub_I(imdiff, J1)
    fig = plt.figure(3)
    plt.clf()
    fig.patch.set_facecolor('white')

    plt.subplot(1, 3, 1)
    display.DispImage(geodesicState.J0,
                      'Source J0',
                      newFig=False,
                      sliceIdx=cf.io.plotSlice)
    plt.colorbar()

    plt.subplot(1, 3, 2)
    display.DispImage(J1, 'Target J1', newFig=False, sliceIdx=cf.io.plotSlice)
    plt.colorbar()

    plt.subplot(1, 3, 3)
    display.DispImage(imdiff,
                      'rho.J0-J1',
                      newFig=False,
                      sliceIdx=cf.io.plotSlice)
    plt.colorbar()
    if cf.io.outputPrefix != None and writeOutput:
        plt.savefig(cf.io.outputPrefix + 'diffImage.pdf')

    # Momenta matching
    if mType == ca.MEM_DEVICE:
        scratchV1 = ca.Field3D(grid, mType)
        scratchV2 = ca.Field3D(grid, mType)
        scratchV3 = ca.Field3D(grid, mType)
    else:
        scratchV1 = ca.ManagedField3D(grid, mType)
        scratchV2 = ca.ManagedField3D(grid, mType)
        scratchV3 = ca.ManagedField3D(grid, mType)

    fig = plt.figure(4)
    plt.clf()
    fig.patch.set_facecolor('white')
    ca.Copy(scratchV1, m0)
    scratchV1.toType(ca.MEM_HOST)
    m0_x, m0_y, m0_z = scratchV1.asnp()
    plt.subplot(2, 3, 1)
    plt.imshow(np.squeeze(m0_x))
    plt.colorbar()
    plt.title('X: Source m0 ')
    plt.subplot(2, 3, 4)
    plt.imshow(np.squeeze(m0_y))
    plt.colorbar()
    plt.title('Y: Source m0')

    ca.Copy(scratchV2, n1)
    scratchV2.toType(ca.MEM_HOST)
    n1_x, n1_y, n1_z = scratchV2.asnp()
    plt.subplot(2, 3, 2)
    plt.imshow(np.squeeze(n1_x))
    plt.colorbar()
    plt.title('X: Target n1')
    plt.subplot(2, 3, 5)
    plt.imshow(np.squeeze(n1_y))
    plt.colorbar()
    plt.title('Y: Target n1')

    ca.CoAd(scratchV3, geodesicState.rhoinv, m0)
    ca.Sub_I(scratchV3, n1)
    scratchV3.toType(ca.MEM_HOST)
    diff_x, diff_y, diff_z = scratchV3.asnp()
    plt.subplot(2, 3, 3)
    plt.imshow(np.squeeze(diff_x))
    plt.colorbar()
    plt.title('X: rho.m0-n1')
    plt.subplot(2, 3, 6)
    plt.imshow(np.squeeze(diff_y))
    plt.colorbar()
    plt.title('Y: rho.m0-n1')

    if cf.io.outputPrefix != None and writeOutput:
        plt.savefig(cf.io.outputPrefix + 'diffMomenta.pdf')

    del scratchV1, scratchV2, scratchV3
    del imdiff
Ejemplo n.º 10
0
    plt.subplot(2, 3, 2)
    display.DispImage(imLargeLinear, 'Linear', newFig=False)
    plt.subplot(2, 3, 3)
    display.DispImage(imLargeCubic, 'Cubic', newFig=False)
    plt.subplot(2, 3, 5)
    display.DispImage(imSmall, 'small', newFig=False)
    plt.show()

    h = common.WavyDef([50, 50],
                       nWaves=1,
                       waveAmp=10,
                       waveDim=0,
                       mType=ca.MEM_HOST,
                       deformation=True)
    imDefNN = imLargeNN.copy()
    ca.ApplyH(imDefNN, imLargeNN, h, ca.BACKGROUND_STRATEGY_CLAMP,
              ca.INTERP_NN)
    imDefLinear = imLargeNN.copy()
    ca.ApplyH(imDefLinear, imLargeNN, h, ca.BACKGROUND_STRATEGY_CLAMP,
              ca.INTERP_LINEAR)
    imDefCubic = imLargeNN.copy()
    ca.ApplyH(imDefCubic, imLargeNN, h, ca.BACKGROUND_STRATEGY_CLAMP,
              ca.INTERP_CUBIC)
    plt.figure('interp def test')
    plt.subplot(2, 3, 1)
    display.DispImage(imDefNN, 'NN', newFig=False)
    plt.subplot(2, 3, 2)
    display.DispImage(imDefLinear, 'Linear', newFig=False)
    plt.subplot(2, 3, 3)
    display.DispImage(imDefCubic, 'Cubic', newFig=False)
    plt.subplot(2, 3, 5)
    display.DispImage(imLargeNN, 'orig', newFig=False)
Ejemplo n.º 11
0
    # convert grid back
    hA.setGrid(grid_orig)
    phi0.setGrid(grid_orig)
    phi.setGrid(grid_orig)
    Idef.setGrid(grid_orig)
    BFI_VE.setGrid(grid_orig)
    MRI_VE.setGrid(grid_orig)

    # Insert Slice back into Volume
    if SaveRGB:
        BFI_color = common.ExtractSliceVF(BFI_color3D, sliceIdx)
        BFI_color.toType(ca.MEM_DEVICE)
        BFI_color.setGrid(grid2D)

        BFI_def_RGB = ca.Field3D(grid2D, BFI.memType())
        ca.ApplyH(BFI_def_RGB, BFI_color, phi,
                  ca.BACKGROUND_STRATEGY_PARTIAL_ZERO)
        cc.InsertSlice(BFIDef3D_RGB, BFI_def_RGB, sliceIdx)
    if SaveVE:
        BFI_def_VE = ca.Image3D(grid2D, BFI.memType())
        ca.ApplyH(BFI_def_VE, BFI_VE, phi, ca.BACKGROUND_STRATEGY_PARTIAL_ZERO)
        cc.InsertSlice(BFIDef3D_VE, BFI_def_VE, sliceIdx)
    if SaveBW:
        BFI_def_BW = ca.Image3D(grid2D, BFI.memType())
        ca.ApplyH(BFI_def_BW, BFI, phi, ca.BACKGROUND_STRATEGY_PARTIAL_ZERO)
        cc.InsertSlice(BFIDef3D_BW, BFI_def_BW, sliceIdx)

# Save BFIDef3D
if SaveInBFICoords:
    print 'saving blockface in blockface coords...'
    if SaveVE:
        cc.WriteMHA(BFIDef3D_VE,
def GeodesicShooting(cf):

    # prepare output directory
    common.Mkdir_p(os.path.dirname(cf.io.outputPrefix))

    # Output loaded config
    if cf.io.outputPrefix is not None:
        cfstr = Config.ConfigToYAML(GeodesicShootingConfigSpec, cf)
        with open(cf.io.outputPrefix + "parsedconfig.yaml", "w") as f:
            f.write(cfstr)

    mType = ca.MEM_DEVICE if cf.useCUDA else ca.MEM_HOST
    #common.DebugHere()
    I0 = common.LoadITKImage(cf.study.I0, mType)
    m0 = common.LoadITKField(cf.study.m0, mType)
    grid = I0.grid()

    ca.ThreadMemoryManager.init(grid, mType, 1)
    # set up diffOp
    if mType == ca.MEM_HOST:
        diffOp = ca.FluidKernelFFTCPU()
    else:
        diffOp = ca.FluidKernelFFTGPU()
    diffOp.setAlpha(cf.diffOpParams[0])
    diffOp.setBeta(cf.diffOpParams[1])
    diffOp.setGamma(cf.diffOpParams[2])
    diffOp.setGrid(grid)

    g = ca.Field3D(grid, mType)
    ginv = ca.Field3D(grid, mType)
    mt = ca.Field3D(grid, mType)
    It = ca.Image3D(grid, mType)
    t = [
        x * 1. / cf.integration.nTimeSteps
        for x in range(cf.integration.nTimeSteps + 1)
    ]
    checkpointinds = range(1, len(t))
    checkpointstates = [(ca.Field3D(grid, mType), ca.Field3D(grid, mType))
                        for idx in checkpointinds]

    scratchV1 = ca.Field3D(grid, mType)
    scratchV2 = ca.Field3D(grid, mType)
    scratchV3 = ca.Field3D(grid, mType)
    # scale momenta to shoot
    cf.study.scaleMomenta = float(cf.study.scaleMomenta)
    if abs(cf.study.scaleMomenta) > 0.000000:
        ca.MulC_I(m0, float(cf.study.scaleMomenta))
        CAvmCommon.IntegrateGeodesic(m0,t,diffOp, mt, g, ginv,\
                                     scratchV1,scratchV2,scratchV3,\
                                     keepstates=checkpointstates,keepinds=checkpointinds,
                                     Ninv=cf.integration.NIterForInverse, integMethod = cf.integration.integMethod)
    else:
        ca.Copy(It, I0)
        ca.Copy(mt, m0)
        ca.SetToIdentity(ginv)
        ca.SetToIdentity(g)

    # write output
    if cf.io.outputPrefix is not None:
        # scale back shotmomenta before writing
        if abs(cf.study.scaleMomenta) > 0.000000:
            ca.ApplyH(It, I0, ginv)
            ca.CoAd(mt, ginv, m0)
            ca.DivC_I(mt, float(cf.study.scaleMomenta))

        common.SaveITKImage(It, cf.io.outputPrefix + "I1.mhd")
        common.SaveITKField(mt, cf.io.outputPrefix + "m1.mhd")
        common.SaveITKField(ginv, cf.io.outputPrefix + "phiinv.mhd")
        common.SaveITKField(g, cf.io.outputPrefix + "phi.mhd")
        GeodesicShootingPlots(g, ginv, I0, It, cf)
        if cf.io.saveFrames:
            SaveFrames(checkpointstates, checkpointinds, I0, It, m0, mt, cf)
def SaveFrames(checkpointstates, checkpointinds, I0, It, m0, mt, cf):
    momentathresh = 0.00002
    common.Mkdir_p(os.path.dirname(cf.io.outputPrefix) + '/frames/')
    image_idx = 0
    fig = plt.figure(1, frameon=False)
    plt.clf()
    display.DispImage(I0,
                      '',
                      newFig=False,
                      cmap='gray',
                      dim=cf.io.plotSliceDim,
                      sliceIdx=cf.io.plotSlice)
    plt.draw()
    outfilename = cf.io.outputPrefix + '/frames/I' + str(image_idx).zfill(
        5) + '.png'
    fig.set_size_inches(4, 4)
    plt.savefig(outfilename, bbox_inches='tight', pad_inches=0, dpi=100)

    fig = plt.figure(2, frameon=False)
    plt.clf()
    temp = ca.Field3D(I0.grid(), I0.memType())
    ca.SetToIdentity(temp)
    common.DebugHere()
    CAvmCommon.MyGridPlot(temp,
                          every=cf.io.gridEvery,
                          color='k',
                          dim=cf.io.plotSliceDim,
                          sliceIdx=cf.io.plotSlice,
                          isVF=False,
                          plotBase=False)
    #fig.patch.set_alpha(0)
    #fig.patch.set_visible(False)
    a = fig.gca()
    #a.set_frame_on(False)
    a.set_xticks([])
    a.set_yticks([])
    plt.axis('tight')
    plt.axis('image')
    plt.axis('off')
    plt.draw()
    fig.set_size_inches(4, 4)
    outfilename = cf.io.outputPrefix + '/frames/invdef' + str(image_idx).zfill(
        5) + '.png'
    plt.savefig(outfilename, bbox_inches='tight', pad_inches=0, dpi=100)

    fig = plt.figure(3, frameon=False)
    plt.clf()
    CAvmCommon.MyGridPlot(temp,
                          every=cf.io.gridEvery,
                          color='k',
                          dim=cf.io.plotSliceDim,
                          sliceIdx=cf.io.plotSlice,
                          isVF=False,
                          plotBase=False)
    #fig.patch.set_alpha(0)
    #fig.patch.set_visible(False)
    a = fig.gca()
    #a.set_frame_on(False)
    a.set_xticks([])
    a.set_yticks([])
    plt.axis('tight')
    plt.axis('image')
    plt.axis('off')
    plt.draw()
    fig.set_size_inches(4, 4)
    outfilename = cf.io.outputPrefix + '/frames/def' + str(image_idx).zfill(
        5) + '.png'
    plt.savefig(outfilename, bbox_inches='tight', pad_inches=0, dpi=100)

    fig = plt.figure(4, frameon=False)
    plt.clf()
    display.DispImage(I0,
                      '',
                      newFig=False,
                      cmap='gray',
                      dim=cf.io.plotSliceDim,
                      sliceIdx=cf.io.plotSlice)
    plt.hold('True')
    CAvmCommon.MyQuiver(m0,
                        dim=cf.io.plotSliceDim,
                        sliceIdx=cf.io.plotSlice,
                        every=cf.io.quiverEvery,
                        thresh=momentathresh,
                        scaleArrows=0.25,
                        arrowCol='r',
                        lineWidth=0.5,
                        width=0.005)
    plt.draw()

    plt.hold('False')

    outfilename = cf.io.outputPrefix + '/frames/m' + str(image_idx).zfill(
        5) + '.png'
    fig.set_size_inches(4, 4)
    plt.savefig(outfilename, bbox_inches='tight', pad_inches=0, dpi=100)

    for i in range(len(checkpointinds)):
        image_idx = image_idx + 1
        ca.ApplyH(It, I0, checkpointstates[i][1])
        fig = plt.figure(1, frameon=False)
        plt.clf()
        display.DispImage(It,
                          '',
                          newFig=False,
                          cmap='gray',
                          dim=cf.io.plotSliceDim,
                          sliceIdx=cf.io.plotSlice)
        plt.draw()
        outfilename = cf.io.outputPrefix + '/frames/I' + str(image_idx).zfill(
            5) + '.png'
        fig.set_size_inches(4, 4)
        plt.savefig(outfilename, bbox_inches='tight', pad_inches=0, dpi=100)

        fig = plt.figure(2, frameon=False)
        plt.clf()
        CAvmCommon.MyGridPlot(checkpointstates[i][1],
                              every=cf.io.gridEvery,
                              color='k',
                              dim=cf.io.plotSliceDim,
                              sliceIdx=cf.io.plotSlice,
                              isVF=False,
                              plotBase=False)
        #fig.patch.set_alpha(0)
        #fig.patch.set_visible(False)
        a = fig.gca()
        #a.set_frame_on(False)
        a.set_xticks([])
        a.set_yticks([])
        plt.axis('tight')
        plt.axis('image')
        plt.axis('off')
        plt.draw()
        outfilename = cf.io.outputPrefix + '/frames/invdef' + str(
            image_idx).zfill(5) + '.png'
        fig.set_size_inches(4, 4)
        plt.savefig(outfilename, bbox_inches='tight', pad_inches=0, dpi=100)

        fig = plt.figure(3, frameon=False)
        plt.clf()
        CAvmCommon.MyGridPlot(checkpointstates[i][0],
                              every=cf.io.gridEvery,
                              color='k',
                              dim=cf.io.plotSliceDim,
                              sliceIdx=cf.io.plotSlice,
                              isVF=False,
                              plotBase=False)
        #fig.patch.set_alpha(0)
        #fig.patch.set_visible(False)
        a = fig.gca()
        #a.set_frame_on(False)
        a.set_xticks([])
        a.set_yticks([])
        plt.axis('tight')
        plt.axis('image')
        plt.axis('off')
        plt.draw()
        outfilename = cf.io.outputPrefix + '/frames/def' + str(
            image_idx).zfill(5) + '.png'
        fig.set_size_inches(4, 4)
        plt.savefig(outfilename, bbox_inches='tight', pad_inches=0, dpi=100)

        ca.CoAd(mt, checkpointstates[i][1], m0)
        fig = plt.figure(4, frameon=False)
        plt.clf()
        display.DispImage(It,
                          '',
                          newFig=False,
                          cmap='gray',
                          dim=cf.io.plotSliceDim,
                          sliceIdx=cf.io.plotSlice)
        plt.hold('True')
        CAvmCommon.MyQuiver(mt,
                            dim=cf.io.plotSliceDim,
                            sliceIdx=cf.io.plotSlice,
                            every=cf.io.quiverEvery,
                            thresh=momentathresh,
                            scaleArrows=0.40,
                            arrowCol='r',
                            lineWidth=0.5,
                            width=0.005)
        plt.draw()
        plt.hold('False')
        outfilename = cf.io.outputPrefix + '/frames/m' + str(image_idx).zfill(
            5) + '.png'
        fig.set_size_inches(4, 4)
        plt.savefig(outfilename, bbox_inches='tight', pad_inches=0, dpi=100)
Ejemplo n.º 14
0
def HGMPlots(cf,
             groupState,
             tDiscGroup,
             residualState,
             tDiscResidual,
             index_individual,
             writeOutput=True):
    """
    Do some summary plots for HGM
    """

    #ENERGY
    fig = plt.figure(1)
    plt.clf()
    fig.patch.set_facecolor('white')

    TE = [sum(x) for x in groupState.EnergyHistory]
    VE = [row[0] for row in groupState.EnergyHistory]
    IE = [row[1] for row in groupState.EnergyHistory]
    SE = [row[2] for row in groupState.EnergyHistory]
    TE = TE[1:]
    VE = VE[1:]
    IE = IE[1:]
    SE = SE[1:]
    plt.subplot(2, 2, 1)
    plt.plot(TE)
    plt.title('Total Energy')
    plt.hold(False)
    plt.subplot(2, 2, 2)
    plt.plot(VE)
    plt.title('Vector Energy')
    plt.hold(False)
    plt.subplot(2, 2, 3)
    plt.plot(IE)
    plt.title('Intercept Energy')
    plt.hold(False)
    plt.subplot(2, 2, 4)
    plt.plot(SE)
    plt.title('Slope Energy')
    plt.hold(False)
    plt.draw()
    plt.show()
    if cf.io.outputPrefix != None and writeOutput:
        plt.savefig(cf.io.outputPrefix + 'energy.pdf')

    # GROUP INITIAL CONDITIONS and PSI and PSI inv
    # shoot group geodesic forward
    CAvmHGMCommon.HGMIntegrateGeodesic(groupState.m0, groupState.t,
                                       groupState.diffOp, groupState.m,
                                       groupState.g, groupState.ginv,
                                       tDiscGroup, groupState.Ninv,
                                       groupState.integMethod)

    fig = plt.figure(2)
    plt.clf()
    fig.patch.set_facecolor('white')

    plt.subplot(2, 2, 1)
    display.DispImage(groupState.I0,
                      'I0',
                      newFig=False,
                      sliceIdx=cf.io.plotSlice)

    plt.subplot(2, 2, 2)
    ca.ApplyH(groupState.I, groupState.I0, groupState.ginv)
    display.DispImage(groupState.I,
                      'I1',
                      newFig=False,
                      sliceIdx=cf.io.plotSlice)

    plt.subplot(2, 2, 3)
    display.GridPlot(groupState.ginv,
                     every=cf.io.quiverEvery,
                     color='k',
                     sliceIdx=cf.io.plotSlice,
                     isVF=False)
    plt.axis('equal')
    plt.axis('off')
    plt.title('psi^{-1}')
    plt.subplot(2, 2, 4)
    display.GridPlot(groupState.g,
                     every=cf.io.quiverEvery,
                     color='k',
                     sliceIdx=cf.io.plotSlice,
                     isVF=False)
    plt.axis('equal')
    plt.axis('off')
    plt.title('psi')
    if cf.io.outputPrefix != None and writeOutput:
        plt.savefig(cf.io.outputPrefix + 'groupdef.pdf')

    # RESIDUAL INITIAL CONDITIONS and RHO and RHO inv
    ca.ApplyH(groupState.I, groupState.I0, groupState.ginv)
    residualState.J0 = groupState.I
    residualState.p0 = tDiscGroup[index_individual].p0
    CAvmHGMCommon.HGMIntegrateGeodesic(residualState.p0, residualState.s,
                                       residualState.diffOp, residualState.p,
                                       residualState.rho, residualState.rhoinv,
                                       tDiscResidual, residualState.Ninv,
                                       residualState.integMethod)

    fig = plt.figure(3)
    plt.clf()
    fig.patch.set_facecolor('white')

    plt.subplot(2, 2, 1)
    display.DispImage(residualState.J0,
                      'J0',
                      newFig=False,
                      sliceIdx=cf.io.plotSlice)
    plt.subplot(2, 2, 2)
    ca.ApplyH(residualState.J, residualState.J0, residualState.rhoinv)
    display.DispImage(residualState.J,
                      'J1',
                      newFig=False,
                      sliceIdx=cf.io.plotSlice)

    plt.subplot(2, 2, 3)
    display.GridPlot(residualState.rhoinv,
                     every=cf.io.quiverEvery,
                     color='k',
                     sliceIdx=cf.io.plotSlice,
                     isVF=False)
    plt.axis('equal')
    plt.axis('off')
    plt.title('rho^{-1}')
    plt.subplot(2, 2, 4)
    display.GridPlot(residualState.rho,
                     every=cf.io.quiverEvery,
                     color='k',
                     sliceIdx=cf.io.plotSlice,
                     isVF=False)
    plt.axis('equal')
    plt.axis('off')
    plt.title('rho')
    if cf.io.outputPrefix != None and writeOutput:
        plt.savefig(cf.io.outputPrefix + 'resdef.pdf')

    # MATCHING DIFFERENCE IMAGES
    grid = groupState.I0.grid()
    mType = groupState.I0.memType()
    imdiff = ca.ManagedImage3D(grid, mType)
    vecdiff = ca.ManagedField3D(grid, mType)

    # Intercept matching
    ca.Copy(imdiff, residualState.J)
    ca.Sub_I(imdiff, tDiscGroup[index_individual].J)
    fig = plt.figure(4)
    plt.clf()
    fig.patch.set_facecolor('white')

    plt.subplot(1, 3, 1)
    display.DispImage(residualState.J0,
                      'Source J0',
                      newFig=False,
                      sliceIdx=cf.io.plotSlice)
    plt.colorbar()

    plt.subplot(1, 3, 2)
    display.DispImage(tDiscGroup[index_individual].J,
                      'Target J1',
                      newFig=False,
                      sliceIdx=cf.io.plotSlice)
    plt.colorbar()

    plt.subplot(1, 3, 3)
    display.DispImage(imdiff,
                      'rho.J0-J1',
                      newFig=False,
                      sliceIdx=cf.io.plotSlice)
    plt.colorbar()
    if cf.io.outputPrefix != None and writeOutput:
        plt.savefig(cf.io.outputPrefix + 'diffintercept.pdf')

    # Slope matching
    '''
    ca.CoAd(groupState.m,groupState.ginv,groupState.m0)
    ca.CoAd(vecdiff,residualState.rhoinv,groupState.m)
    n0 = ca.Field3D(grid, ca.MEM_HOST)
    n1 = ca.Field3D(grid, ca.MEM_HOST)
    ca.Copy(n0,groupState.m)
    ca.Copy(n1,tDiscGroup[index_individual].n)    
    ca.Sub_I(vecdiff, tDiscGroup[index_individual].n)
    vecdiff.toType(ca.MEM_HOST)
    n0_x, n0_y, n0_z = n0.asnp()
    n1_x, n1_y, n1_z = n1.asnp()
    diff_x, diff_y, diff_z = vecdiff.asnp()

    fig = plt.figure(5)
    plt.clf()
    fig.patch.set_facecolor('white')

    plt.subplot(2,3,1)
    plt.imshow(np.squeeze(n0_x)); plt.colorbar(); plt.title('X: Source n0 ')

    plt.subplot(2,3,2)
    plt.imshow(np.squeeze(n1_x)); plt.colorbar(); plt.title('X: Target n1')

    plt.subplot(2,3,3)
    plt.imshow(np.squeeze(diff_x)); plt.colorbar(); plt.title('X: rho.n0-n1')

    plt.subplot(2,3,4)
    plt.imshow(np.squeeze(n0_y)); plt.colorbar(); plt.title('Y: Source n0')

    plt.subplot(2,3,5)
    plt.imshow(np.squeeze(n1_y)); plt.colorbar(); plt.title('Y: Target n1')

    plt.subplot(2,3,6)
    plt.imshow(np.squeeze(diff_y)); plt.colorbar(); plt.title('Y: rho.n0-n1')

    if cf.io.outputPrefix != None and writeOutput: plt.savefig(cf.io.outputPrefix+'diffslope.pdf')
    '''
    del imdiff
    del vecdiff
Ejemplo n.º 15
0
def MatchingPlots(p):
    """
    Do some summary plots for image matching
    """
    #reset all variables by shooting once, may have been overwritten
    CAvmCommon.IntegrateGeodesic(p.m0,p.t,p.diffOp,\
                          p.m, p.g, p.ginv,\
                          p.scratchV1, p.scratchV2,p. scratchV3,\
                          p.checkpointstates, p.checkpointinds,\
                          Ninv=p.nInv, integMethod = p.integMethod)

    # plot the images
    fig = plt.figure('images')
    plt.clf()
    fig.patch.set_facecolor('white')
    plt.subplot(2, 2, 1)
    display.DispImage(p.I0,
                      'I0',
                      newFig=False,
                      cmap='gray',
                      sliceIdx=p.plotSlice)
    plt.subplot(2, 2, 2)
    indx_of_last_tp = p.checkpointinds.index(len(p.t) - 1)
    (g, ginv) = p.checkpointstates[indx_of_last_tp]
    ca.ApplyH(p.I, p.I0, ginv)
    display.DispImage(p.I,
                      '\phi.I0',
                      newFig=False,
                      cmap='gray',
                      sliceIdx=p.plotSlice)
    plt.subplot(2, 2, 3)
    display.DispImage(p.I1,
                      'I1',
                      newFig=False,
                      cmap='gray',
                      sliceIdx=p.plotSlice)
    plt.subplot(2, 2, 4)
    ca.ApplyH(p.I, p.I1, g)
    display.DispImage(p.I,
                      '\phi^{-1}.I1',
                      newFig=False,
                      cmap='gray',
                      sliceIdx=p.plotSlice)

    plt.draw()
    plt.show()
    if p.outputPrefix != None: plt.savefig(p.outputPrefix + 'images.pdf')
    fig = plt.figure('def')
    plt.clf()
    fig.patch.set_facecolor('white')
    plt.subplot(2, 2, 1)
    display.GridPlot(ginv,
                     every=p.quiverEvery,
                     color='k',
                     sliceIdx=p.plotSlice,
                     isVF=False)
    plt.axis('equal')
    plt.axis('off')
    plt.title('\phi^{-1}')
    plt.subplot(2, 2, 2)
    display.GridPlot(g,
                     every=p.quiverEvery,
                     color='k',
                     sliceIdx=p.plotSlice,
                     isVF=False)
    plt.axis('equal')
    plt.axis('off')
    plt.title('\phi')
    plt.subplot(2, 2, 3)
    ca.JacDetH(p.I, ginv)  #p.I used as scratch variable to compute jacobian
    display.DispImage(p.I, '|D\phi^{-1}|', newFig=False, sliceIdx=p.plotSlice)
    plt.subplot(2, 2, 4)
    ca.MulC_I(p.residualIm, p.sigma * p.sigma)
    display.DispImage(p.residualIm,
                      '\phi.I0-I1',
                      newFig=False,
                      sliceIdx=p.plotSlice)
    plt.colorbar()
    plt.draw()
    plt.show()
    if p.outputPrefix != None: plt.savefig(p.outputPrefix + 'def.pdf')
    fig = plt.figure('energy')
    fig.patch.set_facecolor('white')

    TE = [sum(x) for x in p.Energy]
    VE = [row[0] for row in p.Energy]
    IE = [row[1] for row in p.Energy]
    plt.subplot(1, 3, 1)
    plt.plot(TE)
    plt.title('Total Energy')
    plt.hold(False)
    plt.subplot(1, 3, 2)
    plt.plot(VE)
    plt.title('Vector Energy')
    plt.hold(False)
    plt.subplot(1, 3, 3)
    plt.plot(IE)
    plt.title('Image Energy')
    plt.hold(False)
    plt.draw()
    plt.show()
    if p.outputPrefix != None: plt.savefig(p.outputPrefix + 'energy.pdf')
Ejemplo n.º 16
0
def ApplyAffine(Iout, Im, A, bg=ca.BACKGROUND_STRATEGY_PARTIAL_ZERO):
    '''Applies an Affine matrix A to an image Im using the Image3D
    grid (size, spacing, origin) of the two images (Input and Output)

    '''
    # algorithm outline:  Create a temporary large grid, then perform
    # real affine transforms here, then crop to be the size of the out grid
    ca.SetMem(Iout, 0.0)

    A = np.matrix(A)

    bigsize = [max(Iout.grid().size().x, Im.grid().size().x),
               max(Iout.grid().size().y, Im.grid().size().y),
               max(Iout.grid().size().z, Im.grid().size().z)]
    idgrid = ca.GridInfo(ca.Vec3Di(bigsize[0], bigsize[1], bigsize[2]),
                         ca.Vec3Df(1, 1, 1),
                         ca.Vec3Df(0, 0, 0))
    # newgrid = Iout.grid()       # not a true copy!!!!!
    newgrid = ca.GridInfo(Iout.grid().size(),
                          Iout.grid().spacing(),
                          Iout.grid().origin())

    mType = Iout.memType()
    Imbig = cc.PadImage(Im, bigsize)
    h = ca.Field3D(idgrid, mType)
    ca.SetToIdentity(h)
    if isinstance(Im, ca.Field3D):
        Ioutbig = ca.Field3D(idgrid, mType)
    else:
        Ioutbig = ca.Image3D(idgrid, mType)

    # note:  x_real' = A*x_real; x_real' given (input grid)
    # solution: x_real = A^-1 * x_real
    # where x_real = x_index*spacing + origin
    # and x_real' = x_index'*spacing' + origin'
    # x_index' is really given, as is both spacings/origins
    # and we plug in the solution for x_index' into applyH

    if A.shape[1] == 3:          # 2D affine matrix
        x = ca.Image3D(idgrid, mType)
        y = ca.Image3D(idgrid, mType)
        xnew = ca.Image3D(idgrid, mType)
        ynew = ca.Image3D(idgrid, mType)
        ca.Copy(x, h, 0)
        ca.Copy(y, h, 1)

        # convert x,y to world coordinates
        x *= Iout.grid().spacing().x
        y *= Iout.grid().spacing().y
        x += Iout.grid().origin().x
        y += Iout.grid().origin().y

        # Matrix Multiply (All in real coords)
        Ainv = A.I
        ca.MulC_Add_MulC(xnew, x, Ainv[0, 0], y, Ainv[0, 1])
        ca.MulC_Add_MulC(ynew, x, Ainv[1, 0], y, Ainv[1, 1])
        xnew += (Ainv[0, 2])
        ynew += (Ainv[1, 2])     # xnew and ynew are now in real coords

        # convert back to index coordinates
        xnew -= Im.grid().origin().x
        ynew -= Im.grid().origin().y
        xnew /= Im.grid().spacing().x
        ynew /= Im.grid().spacing().y

        ca.SetToZero(h)
        ca.Copy(h, xnew, 0)
        ca.Copy(h, ynew, 1)

    elif A.shape[1] == 4:         # 3D affine matrix
        x = ca.Image3D(idgrid, mType)
        y = ca.Image3D(idgrid, mType)
        z = ca.Image3D(idgrid, mType)
        xnew = ca.Image3D(idgrid, mType)
        ynew = ca.Image3D(idgrid, mType)
        znew = ca.Image3D(idgrid, mType)
        ca.Copy(x, h, 0)
        ca.Copy(y, h, 1)
        ca.Copy(z, h, 2)

        x *= Iout.grid().spacing().x
        y *= Iout.grid().spacing().y
        z *= Iout.grid().spacing().z
        x += Iout.grid().origin().x
        y += Iout.grid().origin().y
        z += Iout.grid().origin().z

        # Matrix Multiply (All in real coords)
        Ainv = A.I
        ca.MulC_Add_MulC(xnew, x, Ainv[0, 0], y, Ainv[0, 1])
        ca.Add_MulC_I(xnew, z, Ainv[0, 2])
        xnew += (Ainv[0, 3])
        ca.MulC_Add_MulC(ynew, x, Ainv[1, 0], y, Ainv[1, 1])
        ca.Add_MulC_I(ynew, z, Ainv[1, 2])
        ynew += (Ainv[1, 3])
        ca.MulC_Add_MulC(znew, x, Ainv[2, 0], y, Ainv[2, 1])
        ca.Add_MulC_I(znew, z, Ainv[2, 2])
        znew += (Ainv[2, 3])

        # convert to index coordinates
        xnew -= Im.grid().origin().x
        ynew -= Im.grid().origin().y
        znew -= Im.grid().origin().z
        xnew /= Im.grid().spacing().x
        ynew /= Im.grid().spacing().y
        znew /= Im.grid().spacing().z

        ca.Copy(h, xnew, 0)
        ca.Copy(h, ynew, 1)
        ca.Copy(h, znew, 2)

    Imbig.setGrid(idgrid)

    ca.ApplyH(Ioutbig, Imbig, h, bg)
    # crop Ioutbig -> Iout
    ca.SubVol(Iout, Ioutbig, ca.Vec3Di(0, 0, 0))
    Iout.setGrid(newgrid)   # change back
Ejemplo n.º 17
0
def Matching(cf):

    if cf.compute.useCUDA and cf.compute.gpuID is not None:
        ca.SetCUDADevice(cf.compute.gpuID)
    if os.path.isfile(cf.io.outputPrefix + 'm0.mhd'):
        print cf.io.outputPrefix
        return ()

    # if os.path.isfile(cf.io.outputPrefix+'m0.mhd'):
    #     return();
    # else:
    #     print cf.io.outputPrefix;
    #     return();
    # prepare output directory
    common.Mkdir_p(os.path.dirname(cf.io.outputPrefix))

    # Output loaded config
    if cf.io.outputPrefix is not None:
        cfstr = Config.ConfigToYAML(MatchingConfigSpec, cf)
        with open(cf.io.outputPrefix + "parsedconfig.yaml", "w") as f:
            f.write(cfstr)

    mType = ca.MEM_DEVICE if cf.compute.useCUDA else ca.MEM_HOST

    I0 = common.LoadITKImage(cf.study.I0, mType)
    I1 = common.LoadITKImage(cf.study.I1, mType)
    #ca.DivC_I(I0,255.0)
    #ca.DivC_I(I1,255.0)
    grid = I0.grid()

    It = ca.Image3D(grid, mType)

    ca.ThreadMemoryManager.init(grid, mType, 1)

    #common.DebugHere()
    # TODO: need to work on these
    t = [x * 1. / cf.optim.nTimeSteps for x in range(cf.optim.nTimeSteps + 1)]
    checkpointinds = range(1, len(t))
    checkpointstates = [(ca.Field3D(grid, mType), ca.Field3D(grid, mType))
                        for idx in checkpointinds]

    p = MatchingVariables(I0,
                          I1,
                          cf.vectormomentum.sigma,
                          t,
                          checkpointinds,
                          checkpointstates,
                          cf.vectormomentum.diffOpParams[0],
                          cf.vectormomentum.diffOpParams[1],
                          cf.vectormomentum.diffOpParams[2],
                          cf.optim.Niter,
                          cf.optim.stepSize,
                          cf.optim.maxPert,
                          cf.optim.nTimeSteps,
                          integMethod=cf.optim.integMethod,
                          optMethod=cf.optim.method,
                          nInv=cf.optim.NIterForInverse,
                          plotEvery=cf.io.plotEvery,
                          plotSlice=cf.io.plotSlice,
                          quiverEvery=cf.io.quiverEvery,
                          outputPrefix=cf.io.outputPrefix)

    print(p.stepSize)

    RunMatching(p)

    # write output
    if cf.io.outputPrefix is not None:
        # reset all variables by shooting once, may have been overwritten
        CAvmCommon.IntegrateGeodesic(p.m0,p.t,p.diffOp,\
                          p.m, p.g, p.ginv,\
                          p.scratchV1, p.scratchV2,p. scratchV3,\
                          p.checkpointstates, p.checkpointinds,\
                          Ninv=p.nInv, integMethod = p.integMethod)
        ca.ApplyH(It, I0, p.ginv)
        common.SaveITKField(p.m0, cf.io.outputPrefix + "m0.mhd")
        common.SaveITKField(p.ginv, cf.io.outputPrefix + "phiinv.mhd")
        #common.SaveITKField(p.g, cf.io.outputPrefix+"phi.mhd")
        common.SaveITKImage(It, cf.io.outputPrefix + "I1.mhd")
def DefReg(I_src, I_tar, config, memT, idConf):

    I_src.toType(memT)
    I_tar.toType(memT)

    # Convert to 2D spacing (because it really matters)
    sp2D = I_src.spacing().tolist()
    sp2D = ca.Vec3Df(sp2D[0], sp2D[1], 1)

    I_tar.setSpacing(sp2D)
    I_src.setSpacing(sp2D)
    gridReg = I_tar.grid()

    # Blur the images
    I_tar_blur = I_tar.copy()
    I_src_blur = I_src.copy()
    temp = ca.Image3D(I_tar.grid(), memT)
    gausFilt = ca.GaussianFilterGPU()

    scaleList = config.scale

    # Initiate the scale manager
    scaleManager = ca.MultiscaleManager(gridReg)
    for s in scaleList:
        scaleManager.addScaleLevel(s)
    if memT == ca.MEM_HOST:
        resampler = ca.MultiscaleResamplerGaussCPU(gridReg)
    else:
        resampler = ca.MultiscaleResamplerGaussGPU(gridReg)

    # Generate the scratch images
    scratchITar = ca.Image3D(gridReg, memT)
    scratchISrc = ca.Image3D(gridReg, memT)
    scratchI = ca.Image3D(gridReg, memT)
    scratchF = ca.Field3D(gridReg, memT)
    compF = ca.Field3D(gridReg, memT)

    def SetScale(scale):
        '''Scale Management for Multiscale'''
        scaleManager.set(scale)
        resampler.setScaleLevel(scaleManager)
        curGrid = scaleManager.getCurGrid()
        curGrid.spacing().z = 1  # Because only 2D

        print 'Inside setScale(). Current grid is ', curGrid

        if scaleManager.isLastScale():
            print 'Inside setScale(): **Last Scale**'
        if scaleManager.isFirstScale():
            print 'Inside setScale(): **First Scale**'

        scratchISrc.setGrid(curGrid)
        scratchITar.setGrid(curGrid)
        scratchI.setGrid(curGrid)
        compF.setGrid(curGrid)
        idConf.study.I0 = ca.Image3D(curGrid, memT)
        idConf.study.I1 = ca.Image3D(curGrid, memT)

        if scaleManager.isLastScale():
            s = config.sigBlur[scaleList.index(sc)]
            r = config.kerBlur[scaleList.index(sc)]
            gausFilt.updateParams(I_tar.size(), ca.Vec3Df(r, r, r),
                                  ca.Vec3Di(s, s, s))
            gausFilt.filter(scratchITar, I_tar, temp)
            gausFilt.filter(scratchI, I_src, temp)

# ca.Copy(scratchI, I_src)
# ca.Copy(scratchITar, I_tar)

        else:
            s = config.sigBlur[scaleList.index(sc)]
            r = config.kerBlur[scaleList.index(sc)]
            gausFilt.updateParams(I_tar.size(), ca.Vec3Df(r, r, r),
                                  ca.Vec3Di(s, s, s))
            gausFilt.filter(I_tar_blur, I_tar, temp)
            gausFilt.filter(I_src_blur, I_src, temp)
            resampler.downsampleImage(scratchI, I_src_blur)
            resampler.downsampleImage(scratchITar, I_tar_blur)

        if scaleManager.isFirstScale():
            scratchF.setGrid(curGrid)
            scratchITar.setGrid(curGrid)
            ca.SetToIdentity(scratchF)
            ca.ApplyH(scratchISrc, scratchI, scratchF)

        else:
            compF.setGrid(scratchF.grid())
            ca.ComposeHH(compF, scratchF, h)
            resampler.updateHField(scratchF)
            resampler.updateHField(compF)
            ca.Copy(scratchF, compF)
            ca.ApplyH(scratchISrc, scratchI, compF)

    for sc in scaleList:
        SetScale(scaleList.index(sc))

        #Set the optimize parameters in the IDiff configuration object
        idConf.optim.Niter = config.iters[scaleList.index(sc)]
        idConf.optim.stepSize = config.epsReg[scaleList.index(sc)]
        idConf.idiff.regWeight = config.sigReg[scaleList.index(sc)]
        ca.Copy(idConf.study.I0, scratchISrc)
        ca.Copy(idConf.study.I1, scratchITar)
        idConf.io.plotEvery = config.iters[scaleList.index(sc)]

        h = IDiff.Matching.Matching(idConf)
        tempScr = scratchISrc.copy()
        ca.ApplyH(tempScr, scratchISrc, h)

        #Plot the images to see the change
        cd.DispImage(scratchISrc - scratchITar,
                     rng=[-2, 2],
                     title='Orig Diff',
                     colorbar=True)
        cd.DispImage(tempScr - scratchITar,
                     rng=[-2, 2],
                     title='Reg Diff',
                     colorbar=True)

        # common.DebugHere()

        # I_src_def = idConf.study.I0.copy()

        # scratchITar = idConf.study.I1
        # eps = config.epsReg[scaleList.index(sc)]
        # sigma = config.sigReg[scaleList.index(sc)]
        # nIter = config.iters[scaleList.index(sc)]
        # # common.DebugHere()
        # [I_src_def, h, energy] = apps.IDiff(scratchISrc, scratchITar, eps, sigma, nIter, plot=True, verbose=1)
    ca.ComposeHH(scratchF, compF, h)
    I_src_def = idConf.study.I0.copy()

    return I_src_def, scratchF