Exemplo n.º 1
0
 def test_GroupAdjointAction(self, disp=False):
     hM = common.RandField(self.sz,
                           nSig=5.0,
                           gSig=4.0,
                           mType=ca.MEM_HOST,
                           sp=self.imSp)
     hV = common.RandField(self.sz,
                           nSig=5.0,
                           gSig=4.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.Field3D(self.grid, ca.MEM_HOST)
     # compute < m, Ad_\phi v >
     ca.Ad(tmp, hPhi, hV)
     rhs = ca.Dot(tmp, hM)
     # compute < Ad^*_\phi m,  v >
     ca.CoAd(tmp, hPhi, hM)
     lhs = ca.Dot(tmp, hV)
     #print "a=%f b=%f" % (rhs, lhs)
     self.assertLess(abs(rhs - lhs), 2e-6)
def predict_each_datapart(args, net, network_config, input_batch, datapart_idx, batch_size, patch_size, predict_transform_space):
    moving_image = torch.load(args.moving_image_dataset[datapart_idx])
    target_image = torch.load(args.target_image_dataset[datapart_idx])
    optimization_momentum = torch.load(args.deformation_parameter[datapart_idx])
    for slice_idx in range(0, moving_image.size()[0]):
        print(slice_idx)
        moving_slice = moving_image[slice_idx].numpy()
        target_slice = target_image[slice_idx].numpy()
        if predict_transform_space:
            moving_slice = util.convert_to_registration_space(moving_slice)
            target_slice = util.convert_to_registration_space(target_slice)

        predicted_momentum = util.predict_momentum(moving_slice, target_slice, input_batch, batch_size, patch_size, net, predict_transform_space);
        m0_reg = common.FieldFromNPArr(predicted_momentum['image_space'], ca.MEM_DEVICE);
            
        moving_image_ca = common.ImFromNPArr(moving_slice, ca.MEM_DEVICE)
        target_image_ca = common.ImFromNPArr(target_slice, ca.MEM_DEVICE)

        registration_result = registration_methods.geodesic_shooting(moving_image_ca, target_image_ca, m0_reg, args.shoot_steps, ca.MEM_DEVICE, network_config)
            
        target_inv = common.AsNPCopy(registration_result['I1_inv'])
        print(target_inv.shape)
        if predict_transform_space:
            target_inv = util.convert_to_predict_space(target_inv)
        print(target_inv.shape)
        target_inv = torch.from_numpy(target_inv)

        target_image[slice_idx] = target_inv

        optimization_momentum[slice_idx] = optimization_momentum[slice_idx] - torch.from_numpy(predicted_momentum['prediction_space'])
        
    torch.save(target_image, args.warped_back_target_output[datapart_idx])
    torch.save(optimization_momentum, args.momentum_residual[datapart_idx])
Exemplo n.º 3
0
 def test_SplatWorldAdjoint(self, disp=False):
     # Random input images
     reg = common.RandImage(self.sz,
                            nSig=1.0,
                            gSig=0.0,
                            mType=ca.MEM_HOST,
                            sp=self.imSp)
     # adjust hJ's grid so that voxels don't align perfectly
     spfactor = 0.77382
     small = common.RandImage(self.sz,
                              nSig=1.0,
                              gSig=0.0,
                              mType=ca.MEM_HOST,
                              sp=self.imSp * spfactor)
     tmpsmall = ca.Image3D(small.grid(), ca.MEM_HOST)
     ca.SetMem(tmpsmall, 0)
     # compute < I(Phi(x)), J(x) >
     ca.ResampleWorld(tmpsmall, reg)
     smallIP = ca.Dot(tmpsmall, small)
     # compute < I(y), |DPhi^{-1}(y)| J(Phi^{-1}(y)) >
     tmpreg = ca.Image3D(reg.grid(), ca.MEM_HOST)
     ca.SetMem(tmpreg, 0)
     ca.SplatWorld(tmpreg, small)
     regIP = ca.Dot(tmpreg, reg)
     #print "a=%f b=%f" % (phiIdotJ, IdotphiJ)
     self.assertLess(abs(smallIP - regIP), 2e-6)
Exemplo n.º 4
0
def gather_file(args):
    if args.momentum:
        file = common.AsNPCopy(common.LoadITKField(args.files[0], ca.MEM_HOST))
    else:
        #file = common.AsNPCopy(common.LoadITKImage(args.files[0], ca.MEM_HOST))
        file = nib.load(args.files[0]).get_data()

    all_size = (len(args.files), ) + (15, 15, 15, 1, 3)  #file.shape;

    data = torch.zeros(all_size)
    for i in range(0, len(args.files)):
        if args.momentum:
            cur_slice = torch.from_numpy(
                common.AsNPCopy(common.LoadITKField(args.files[i],
                                                    ca.MEM_HOST)))
        else:
            cur_slice = nib.load(args.files[i]).get_data()
            if cur_slice.size == 3375:
                cur_slice = np.zeros([15, 15, 15, 1, 3])
            cur_slice = torch.from_numpy(cur_slice)
        data[i] = cur_slice

    if args.momentum:
        # transpose the dataset to fit the training format
        data = data.numpy()
        data = np.transpose(data, [0, 4, 1, 2, 3])
        data = torch.from_numpy(data)

    torch.save(data, args.output)
Exemplo n.º 5
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)
def AtlasWriteOutput(cf, atlas, m_array, nodeSubjectsIds, isReporter):
    # save initial momenta for all individuals
    for itsub in range(len(nodeSubjectsIds)):
        common.SaveITKField(
            m_array[itsub], cf.io.outputPrefix +
            str(nodeSubjectsIds[itsub]).replace('.', '_') + "_m0.mhd")

    # save the atlas
    if isReporter:
        common.SaveITKImage(atlas, cf.io.outputPrefix + "atlas.mhd")
Exemplo n.º 7
0
def GeoRegWriteOuput(subjectId, cf, p, t, Imsmts, cpinds, cpstates, msmtinds,
                     gradAtMsmts, EnergyHistory):
    # save initial image and momenta for regression geodesic
    common.SaveITKImage(p.I0, cf.io.outputPrefix + subjectId + "I0.mhd")
    common.SaveITKField(p.m0, cf.io.outputPrefix + subjectId + "m0.mhd")

    # save residual images for regression geodesic
    # TODO:

    # write Energy details
    energyFilename = cf.io.outputPrefix + subjectId + "Energy.csv"
    with open(energyFilename, 'w') as f:
        csv_writer = csv.writer(f, delimiter='\t')
        csv_writer.writerows(EnergyHistory)
def MyQuiver(vf, sliceIdx=None, dim='z',every=1,thresh=None,scaleArrows=None,arrowCol='r',lineWidth=None, width=None):
    sliceArr = common.ExtractSliceArrVF(vf, sliceIdx, dim)    
    if dim=='z':
         vy = np.squeeze(sliceArr[:,:,0])
         vx = np.squeeze(sliceArr[:,:,1])
    elif dim=='x':
         vy = np.squeeze(sliceArr[:,:,1])
         vx = np.squeeze(sliceArr[:,:,2])
    elif dim=='y':
         vy = np.squeeze(sliceArr[:,:,0])
         vx = np.squeeze(sliceArr[:,:,2])
    vxshow = np.zeros(np.shape(vx))
    vyshow = np.zeros(np.shape(vy))
    
    vxshow[::every,::every] = vx[::every,::every]
    vyshow[::every,::every] = vy[::every,::every] 
    valindex = np.zeros(np.shape(vx),dtype=bool)
    valindex[::every,::every] = True
    
    if thresh is not None:
        valindex[(vx**2+vy**2)<thresh] = False


    #gridX, gridY = np.meshgrid(range(np.shape(vx)[0]),range(np.shape(vx)[1]-1,-1,-1))
    gridX, gridY = np.meshgrid(range(np.shape(vx)[0]),range(np.shape(vx)[1]))
    quiverhandle = plt.quiver(gridX[valindex],gridY[valindex],vx[valindex],vy[valindex],scale=scaleArrows,color=arrowCol,linewidth=lineWidth,width=width,zorder=4)

    # change axes to match image axes 
    plt.gca().invert_yaxis()

    # force redraw
    plt.draw()
def intensity_normalization_histeq(args):
    for i in range(0, len(args.input_images)):
        image = common.LoadITKImage(args.output_images[i], ca.MEM_HOST)
        grid = image.grid()
        image_np = common.AsNPCopy(image)
        nan_mask = np.isnan(image_np)
        image_np[nan_mask] = 0
        image_np /= np.amax(image_np)

        # perform histogram equalization if needed
        if args.histeq:
            image_np[image_np != 0] = exposure.equalize_hist(
                image_np[image_np != 0])
        image_result = common.ImFromNPArr(image_np, ca.MEM_HOST)
        image_result.setGrid(grid)
        common.SaveITKImage(image_result, args.output_images[i])
Exemplo n.º 10
0
 def randHSetUp(self):
     self.hRandH = \
         common.RandField(self.sz, nSig=5.0, gSig=4.0,
                          mType = MEM_HOST, sp = self.imSp)
     VtoH_I(self.hRandH)
     self.dRandH = self.hRandH.copy()
     self.dRandH.toType(MEM_DEVICE)
Exemplo n.º 11
0
def GridPlot(vf, sliceIdx=None, dim='z', every=1,
             isVF=True, color='g', plotBase=True, colorbase='#A0A0FF'):
    sliceArr = np.squeeze(common.ExtractSliceArrVF(vf, sliceIdx, dim))
    sz = sliceArr.shape
    hID = np.mgrid[0:sz[0], 0:sz[1]]
    d1 = np.squeeze(hID[1, ::every, ::every])
    d2 = np.squeeze(hID[0, ::every, ::every])
    sliceArr = sliceArr[::every, ::every, :]
    if plotBase:
        plt.plot(d1, d2, colorbase)
        plt.hold(True)
        plt.plot(d1.T, d2.T, colorbase)
    if not isVF:
        d1 = np.zeros(d1.shape)
        d2 = np.zeros(d2.shape)
    plt.plot(d1+np.squeeze(sliceArr[:,:,1]),
             d2+np.squeeze(sliceArr[:,:,0]), color)
    plt.hold(True)
    plt.plot((d1+np.squeeze(sliceArr[:,:,1])).T,
             (d2+np.squeeze(sliceArr[:,:,0])).T, color)
    plt.hold(False)
    # change axes to match image axes
    if not plt.gca().yaxis_inverted():
        plt.gca().invert_yaxis()
        # force redraw
        plt.draw()
Exemplo n.º 12
0
 def randVPair(self):
     hV = common.RandField(self.sz,
                           nSig=5.0,
                           gSig=4.0,
                           mType=MEM_HOST,
                           sp=self.imSp)
     dV = hV.copy()
     dV.toType(MEM_DEVICE)
     return hV, dV
Exemplo n.º 13
0
 def randMaskSetUp(self):
     randArr = np.random.rand(self.sz[0], self.sz[1])
     maskArr = np.zeros(randArr.shape)
     maskArr[randArr > 0.5] = 1.0
     self.hRandMask = common.ImFromNPArr(maskArr,
                                         mType=MEM_HOST,
                                         sp=self.imSp)
     self.dRandMask = self.hRandMask.copy()
     self.dRandMask.toType(MEM_DEVICE)
Exemplo n.º 14
0
 def test_ResampleInterp(self, disp=False):
     # generate small integer-valued image
     initMax = 5
     randArrSmall = (np.random.rand(10, 10) * initMax).astype(int)
     randImSmall = common.ImFromNPArr(randArrSmall)
     imLarge = Image3D(50, 50, 1)
     Resample(imLarge, randImSmall, BACKGROUND_STRATEGY_CLAMP, INTERP_NN)
     nUnique = len(np.unique(imLarge.asnp()))
     self.assertEqual(nUnique, initMax)
Exemplo n.º 15
0
def Quiver(vf, sliceIdx=None, dim='z'):
    sliceArr = common.ExtractSliceArrVF(vf, sliceIdx, dim)
    plt.quiver(np.squeeze(sliceArr[:,:,0]).T,
               np.squeeze(sliceArr[:,:,1]).T,
               scale=None)
    # change axes to match image axes
    if not plt.gca().yaxis_inverted():
        plt.gca().invert_yaxis()
        # force redraw
        plt.draw()
def main():

	secNum = sys.argv[1]
	mkyNum = sys.argv[2]
	channel = sys.argv[3]
	region = str(sys.argv[4])

	conf_dir = '/home/sci/blakez/korenbergNAS/3D_database/Working/Microscopic/confocal/src_registration/'
	side_dir = '/home/sci/blakez/korenbergNAS/3D_database/Working/Microscopic/side_light_microscope/src_registration/'
	save_dir = '/home/sci/blakez/korenbergNAS/3D_database/Working/Microscopic/confocal/sidelight_registered/'

	# DIC = '/home/sci/blakez/Reflect Affine/DIC_to_Reflect.txt'
	src_pt = conf_dir + 'M{0}/section_{1}/{2}/section_{1}_confocal_relation_with_sidelight.txt'.format(mkyNum, secNum, region)
	tar_pt = side_dir + 'M{0}/section_{1}/section_{1}_sidelight_relation_with_confocal.txt'.format(mkyNum, secNum)
	# SID = '/home/sci/blakez/Reflect Affine/sidelight_to_DIC.txt'

	src_im = common.LoadITKImage(conf_dir + 'M{0}/section_{1}/{3}/Ch{2}/M{0}_{1}_LGN_RHS_Ch{2}_z00.tif'.format(mkyNum, secNum, channel, region))
	# tar_im = common.LoadITKImage('M{0}/{1}/Crop_ThirdNerve_EGFP_z16.tiff'.format(mkyNum, secNum))

	# The points need to be chosen in the origin corrected sidescape for downstream purposes
	affine = load_and_solve(tar_pt, src_pt)
	out_grid = bb_grid_solver(src_im, affine)

	z_stack = []
	num_slices = len(glob.glob(conf_dir + 'M{0}/section_{1}/{3}/Ch{2}/*'.format(mkyNum, secNum, channel, region)))

	for z in range(0, num_slices):

		src_im = common.LoadITKImage(conf_dir + 'M{0}/section_{1}/{4}/Ch{2}/M{0}_{1}_LGN_RHS_Ch{2}_z{3}.tif'.format(mkyNum, secNum, channel, str(z).zfill(2), region))
		aff_im = ca.Image3D(out_grid, ca.MEM_HOST)
		cc.ApplyAffineReal(aff_im, src_im, affine)
		common.SaveITKImage(aff_im, save_dir + 'M{0}/section_{1}/{4}/Ch{2}/M{0}_01_section_{1}_LGN_RHS_Ch{2}_conf_aff_sidelight_z{3}.tiff'.format(mkyNum, secNum, channel, str(z).zfill(2), region))
		z_stack.append(aff_im)
		print('==> Done with {0}/{1}'.format(z, num_slices - 1))


	stacked = cc.Imlist_to_Im(z_stack)
	stacked.setSpacing(ca.Vec3Df(out_grid.spacing()[0], out_grid.spacing()[1], 0.03/num_slices))
	common.SaveITKImage(stacked, save_dir + 'M{0}/section_{1}/{3}/Ch{2}/M{0}_01_section_{1}_Ch{2}_conf_aff_sidelight_stack.nrrd'.format(mkyNum, secNum, channel, region))
	common.DebugHere()
	if channel==0:
		cc.WriteGrid(stacked.grid(), save_dir + 'M{0}/section_{1}/{2}/affine_registration_grid.txt'.format(mkyNum, secNum, region))
Exemplo n.º 17
0
def DispImage(im, title=None,
              sliceIdx=None, dim='z',
              cmap='gray', newFig=True,
              rng=None, t=False, log=False):

    # if this volume is not a slice already, extract a slice
    sz = im.size().tolist()
    if sz[common.DIMMAP[dim]] > 1:
        im = common.ExtractSliceIm(im, sliceIdx, dim)
        im.toType(core.MEM_HOST)

    # transfer to host memory if necessary
    if im.memType() == core.MEM_DEVICE:
        tmp = core.Image3D(im.grid(), core.MEM_HOST)
        core.Copy(tmp, im)
        im = tmp
        
    # create the figure if requested
    if newFig:
        if title is None:
            plt.figure()
        else:
            plt.figure(title)
        plt.clf()
            
    # set the range
    if rng is None:
        vmin = None
        vmax = None
    else:
        vmin = rng[0]
        vmax = rng[1]

    if log:
        norm = matplotlib.colors.LogNorm(vmin=vmin, vmax=vmax)
    else:
        norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)

    # convert to numpy array
    arr = np.squeeze(im.asnp().copy())

    # transpose if requested
    if t:
        arr = arr.T

    # display
    plt.imshow(arr, cmap=cmap, vmin=vmin, vmax=vmax, norm=norm, interpolation='nearest')
    plt.axis('tight')
    plt.axis('image')
    if title is not None:
        plt.title(title)
    plt.xticks([])
    plt.yticks([])
    plt.draw()
def Loader(cfOb, memT):
    '''Function for loading all of the images. All images get normalized between 0 and 1'''

    #Load Source Images
    bfiSrc = cc.LoadColorMHA(
        pth.expanduser(secOb.bfiSrcPath + cfOb.bfiSrcName), memT)
    ssiSrc = common.LoadITKImage(
        pth.expanduser(secOb.ssiSrcPath + cfOb.ssiSrcName), memT)
    ssiSrc /= ca.Max(ssiSrc)

    #Load Mask Image
    bfiMsk = common.LoadITKImage(
        pth.expanduser(secOb.bfiMskPath + cfOb.bfiMskName), memT)
    bfiMsk /= ca.Max(bfiMsk)
    bfiMsk.setGrid(bfiSrc.grid())
    ssiMsk = common.LoadITKImage(
        pth.expanduser(secOb.ssiMskPath + cfOb.ssiMskName), memT)
    ssiMsk /= ca.Max(ssiMsk)

    return ssiSrc, bfiSrc, ssiMsk, bfiMsk
Exemplo n.º 19
0
def preprocess_image(image_pyca, histeq):
    image_np = common.AsNPCopy(image_pyca)
    nan_mask = np.isnan(image_np)
    image_np[nan_mask] = 0
    image_np /= np.amax(image_np)

    # perform histogram equalization if needed
    if histeq:
        image_np[image_np != 0] = exposure.equalize_hist(image_np[image_np != 0])

    return image_np
Exemplo n.º 20
0
def HGMWriteOutput(cf, groupState, tDiscGroup, isReporter):
    # save initial momenta for residual geodesics, p, for all individuals
    for i in range(len(groupState.t)):
        if tDiscGroup[i].J is not None:
            common.SaveITKField(
                tDiscGroup[i].p0, cf.io.outputPrefix +
                str(tDiscGroup[i].subjectId).replace('.', '_') + "_p0.mhd")
            # write individual's energy history
            energyFilename = cf.io.outputPrefix + str(
                tDiscGroup[i].subjectId).replace('.',
                                                 '_') + "ResidualEnergy.csv"
            HGMWriteEnergyHistoryToFile(tDiscGroup[i].Energy, energyFilename)

    # save initial image and momenta for group gedoesic
    if isReporter:
        common.SaveITKImage(groupState.I0, cf.io.outputPrefix + "I0.mhd")
        common.SaveITKField(groupState.m0, cf.io.outputPrefix + "m0.mhd")
        # write energy history
        energyFilename = cf.io.outputPrefix + "TotalEnergyHistory.csv"
        HGMWriteEnergyHistoryToFile(groupState.EnergyHistory, energyFilename)
Exemplo n.º 21
0
def Load(spec, argv):
    """Load YAML file, validate it, given spec (inserting defaults) and convert
    to attributes
    """
    if len(argv) < 2:
        print('# Usage: ' + argv[0] + ' <config.yaml>')
        print('# Below is a sample config YAML file')
        print(SpecToYAML(spec))
        print('# PyCA Version: %s (%s)' %
              (common.PyCAVersion(), common.PyCABranch()))
        if '_resource' in spec:
            # this won't be printed by default, but let's keep track
            print("_resource: " + spec['_resource'])

        raise MissingConfigError()

    d = LoadYAMLDict(argv[1])

    # TODO: process overrides (given on the cmdline as key=value pairs)

    return MkConfig(d, spec)
Exemplo n.º 22
0
 def test_AddMasked(self, disp=False):
     SetMem(self.hIm, 0.0)
     SetMem(self.dIm, 0.0)
     hIm2 = common.RandImage(self.sz,
                             nSig=1.0,
                             gSig=0.0,
                             mType=MEM_HOST,
                             sp=self.imSp)
     dIm2 = hIm2.copy()
     dIm2.toType(MEM_DEVICE)
     Add(self.hIm, self.hRandIm, hIm2, self.hRandMask)
     Add(self.dIm, self.dRandIm, dIm2, self.dRandMask)
     self.TestIm(self.hIm, self.dIm, name='AddMasked', disp=disp)
Exemplo n.º 23
0
def JacDetPlot(vf, title='Jac. Det.',
               jd_max=10.0, cmap='PRGn',
               nonpos_clr=(1.0, 0.0, 0.0, 1.0),
               sliceIdx=None, dim='z',
               isVF=True,
               newFig=False):
    """
    Plot the jacobian determinant using logmapped colors, and setting
    zero or negative values to 'nonpos_clr'.  jd_max is the maximum
    value to display without clamping, and also defines the min value
    as 1.0/jd_max to assure 1.0 is centered in the colormap.  If vf is
    a vector field, compute the jacobian determinant.  If it is an
    Image3D, assume it is the jacobian determinant to be plotted.
    """

    if common.IsField3D(vf):
        grid = vf.grid()
        mType = vf.memType()
        h = core.ManagedField3D(grid, mType)
        jacdet = core.ManagedImage3D(grid, mType)
        core.Copy(h, vf)
        if isVF:
            core.VtoH_I(h)
        core.JacDetH(jacdet, h)
    elif common.IsImage3D(vf):
        jacdet = vf
    else:
        raise Exception('unknown input type to JacDetPlot, %s'%\
                        str(type(vf)))
    jd_cmap = JacDetCMap(jd_max=jd_max, cmap=cmap,
                               nonpos_clr=nonpos_clr)
    DispImage(jacdet, title=title,
              sliceIdx=sliceIdx, dim=dim,
              rng=[1.0/jd_max, jd_max],
              cmap=jd_cmap,
              log=True,
              newFig=newFig)
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)
Exemplo n.º 25
0
def SaveSlice(fname, im, sliceIdx=None, dim='z',
              cmap='gray', rng=None, t=True):
    sliceIm = common.ExtractSliceIm(im, sliceIdx, dim)
    sliceIm.toType(core.MEM_HOST)
    if rng is None:
        vmin = None
        vmax = None
    else:
        vmin = rng[0]
        vmax = rng[1]
    if t:
        plt.imsave(fname, np.squeeze(sliceIm.asnp()).T,
                   cmap=cmap, vmin=vmin, vmax=vmax)
    else:
        plt.imsave(fname, np.squeeze(sliceIm.asnp()),
                   cmap=cmap, vmin=vmin, vmax=vmax)
Exemplo n.º 26
0
    def __init__(self, methodName='runTest'):
        super(CpuGpuTestCase, self).__init__(methodName)

        self.cudaEnabled = (GetNumberOfCUDADevices() > 0)

        if self.cudaEnabled:
            # allowable average abs. diff
            self.AvEps = 1e-6
            # allowable max abs. diff
            self.MaxEps = 1e-4
            # image size
            self.sz = np.array([127, 119])
            # spacing
            self.sp = np.array([1.5, 2.1])
            # fluid parameters
            self.fluidParams = [1.0, 1.0, 0.0]

            self.vsz = np.append(self.sz, 2)
            self.imSz = Vec3Di(int(self.sz[0]), int(self.sz[1]), 1)
            self.imSp = Vec3Df(float(self.sp[0]), float(self.sp[1]), 1.0)
            # set up grid
            self.grid = GridInfo(self.imSz, self.imSp)

            # set up host / device images
            self.I0Arr = common.DrawEllipse(self.sz, self.sz / 2,
                                            self.sz[0] / 4, self.sz[1] / 3)
            self.I1Arr = common.DrawEllipse(self.sz, self.sz / 2,
                                            self.sz[0] / 3, self.sz[1] / 4)

            self.I0Arr = common.GaussianBlur(self.I0Arr, 1.5)
            self.I1Arr = common.GaussianBlur(self.I1Arr, 1.5)

            self.hI0Orig = common.ImFromNPArr(self.I0Arr,
                                              mType=MEM_HOST,
                                              sp=self.imSp)
            self.hI1Orig = common.ImFromNPArr(self.I1Arr,
                                              mType=MEM_HOST,
                                              sp=self.imSp)
            self.dI0Orig = common.ImFromNPArr(self.I0Arr,
                                              mType=MEM_DEVICE,
                                              sp=self.imSp)
            self.dI1Orig = common.ImFromNPArr(self.I1Arr,
                                              mType=MEM_DEVICE,
                                              sp=self.imSp)
Exemplo n.º 27
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
Exemplo n.º 28
0
def Matching(cf):

    if cf.compute.useCUDA and cf.compute.gpuID is not None:
        ca.SetCUDADevice(cf.compute.gpuID)

    # 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()

    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)

    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)
        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")
Exemplo n.º 29
0
                BFIfname = 'block{0}_reg_fillblanks_{1}_hd4.mha'.format(block, color)
            # BFI = cc.LoadMHA(BFIdir + BFIfname, mType)
#            outimage = common.ExtractSliceIm(BFI,100)
            cd.Disp3Pane(BFI_aff)
            
            if color in ['bw', 've', 'weight']:
                BFIdef = ca.ManagedImage3D(MRIgrid, mType)  # these should be small enough
            else:
                BFIdef = ca.ManagedField3D(MRIgrid, mType)
            cc.ApplyHReal(BFIdef, BFI_aff, h)
            if sz == MRIsizes[-1] and color == colors[-1]:
                cd.Disp3Pane(BFIdef)

            # write data
            if Write:
                if color == 'rgb':
                    fname = 'block{0}_as_MRI_rgba_{1}.mha'.format(block, sz)
                    cc.WriteColorMHA(BFIdef, outdir + fname)
                    fname = 'block{0}_as_MRI_rgb_{1}.mha'.format(block, sz)
                    cc.WriteMHA(BFIdef, outdir + fname)
                else:
                    #fname = 'block{0}_as_MRI_{1}_{2}_NEWLANDMARKS.mha'.format(block, color, sz)
                    fname = 'M15_01_to_MRI_TPS_bw_256_VE.mha'
                    cc.WriteMHA(BFIdef, outdir + fname)
                    cc.WriteMHA(h, outdir + 'M15_01_to_MRI_TPS_def_256.mha')
                    # cc.WriteMHA(h, outdir + 'block{0}_TPS_HField_{1}.mha'.format(block,sz))
                    cd.Disp3Pane(BFIdef)
            common.DebugHere()
            del BFIdef, BFI
        del h
def main():
    secNum = sys.argv[1]
    mkyNum = sys.argv[2]
    region = str(sys.argv[3])
    # channel = sys.argv[3]
    ext = 'M{0}/section_{1}/{2}/'.format(mkyNum, secNum, region)
    ss_dir = '/home/sci/blakez/korenbergNAS/3D_database/Working/Microscopic/side_light_microscope/'
    conf_dir = '/home/sci/blakez/korenbergNAS/3D_database/Working/Microscopic/confocal/'
    memT = ca.MEM_DEVICE

    try:
        with open(
                ss_dir +
                'src_registration/M{0}/section_{1}/M{0}_01_section_{1}_regions.txt'
                .format(mkyNum, secNum), 'r') as f:
            region_dict = json.load(f)
            f.close()
    except IOError:
        region_dict = {}
        region_dict[region] = {}
        region_dict['size'] = map(
            int,
            raw_input("What is the size of the full resolution image x,y? ").
            split(','))
        region_dict[region]['bbx'] = map(
            int,
            raw_input(
                "What are the x indicies of the bounding box (Matlab Format x_start,x_stop? "
            ).split(','))
        region_dict[region]['bby'] = map(
            int,
            raw_input(
                "What are the y indicies of the bounding box (Matlab Format y_start,y_stop? "
            ).split(','))

    if region not in region_dict:
        region_dict[region] = {}
        region_dict[region]['bbx'] = map(
            int,
            raw_input(
                "What are the x indicies of the bounding box (Matlab Format x_start,x_stop? "
            ).split(','))
        region_dict[region]['bby'] = map(
            int,
            raw_input(
                "What are the y indicies of the bounding box (Matlab Format y_start,y_stop? "
            ).split(','))

    img_region = common.LoadITKImage(
        ss_dir +
        'src_registration/M{0}/section_{1}/M{0}_01_section_{1}_{2}.tiff'.
        format(mkyNum, secNum, region), ca.MEM_HOST)
    ssiSrc = common.LoadITKImage(
        ss_dir +
        'src_registration/M{0}/section_{1}/frag0/M{0}_01_ssi_section_{1}_frag0.nrrd'
        .format(mkyNum, secNum), ca.MEM_HOST)
    bfi_df = common.LoadITKField(
        ss_dir +
        'Blockface_registered/M{0}/section_{1}/frag0/M{0}_01_ssi_section_{1}_frag0_to_bfi_real.mha'
        .format(mkyNum, secNum), ca.MEM_DEVICE)

    # Figure out the same region in the low resolution image: There is a transpose from here to matlab so dimensions are flipped
    low_sz = ssiSrc.size().tolist()
    yrng_raw = [(low_sz[1] * region_dict[region]['bbx'][0]) /
                np.float(region_dict['size'][0]),
                (low_sz[1] * region_dict[region]['bbx'][1]) /
                np.float(region_dict['size'][0])]
    xrng_raw = [(low_sz[0] * region_dict[region]['bby'][0]) /
                np.float(region_dict['size'][1]),
                (low_sz[0] * region_dict[region]['bby'][1]) /
                np.float(region_dict['size'][1])]
    yrng = [np.int(np.floor(yrng_raw[0])), np.int(np.ceil(yrng_raw[1]))]
    xrng = [np.int(np.floor(xrng_raw[0])), np.int(np.ceil(xrng_raw[1]))]
    low_sub = cc.SubVol(ssiSrc, xrng, yrng)

    # Figure out the grid for the sub region in relation to the sidescape
    originout = [
        ssiSrc.origin().x + ssiSrc.spacing().x * xrng[0],
        ssiSrc.origin().y + ssiSrc.spacing().y * yrng[0], 0
    ]
    spacingout = [
        (low_sub.size().x * ssiSrc.spacing().x) / (img_region.size().x),
        (low_sub.size().y * ssiSrc.spacing().y) / (img_region.size().y), 1
    ]

    gridout = cc.MakeGrid(img_region.size().tolist(), spacingout, originout)
    img_region.setGrid(gridout)

    only_sub = np.zeros(ssiSrc.size().tolist()[0:2])
    only_sub[xrng[0]:xrng[1], yrng[0]:yrng[1]] = np.squeeze(low_sub.asnp())
    only_sub = common.ImFromNPArr(only_sub)
    only_sub.setGrid(ssiSrc.grid())

    # Deform the only sub region to
    only_sub.toType(ca.MEM_DEVICE)
    def_sub = ca.Image3D(bfi_df.grid(), bfi_df.memType())
    cc.ApplyHReal(def_sub, only_sub, bfi_df)
    def_sub.toType(ca.MEM_HOST)

    # Now have to find the bounding box in the deformation space (bfi space)
    if 'deformation_bbx' not in region_dict[region]:
        bb_def = np.squeeze(pp.LandmarkPicker([np.squeeze(def_sub.asnp())]))
        bb_def_y = [bb_def[0][0], bb_def[1][0]]
        bb_def_x = [bb_def[0][1], bb_def[1][1]]
        region_dict[region]['deformation_bbx'] = bb_def_x
        region_dict[region]['deformation_bby'] = bb_def_y

    with open(
            ss_dir +
            'src_registration/M{0}/section_{1}/M{0}_01_section_{1}_regions.txt'
            .format(mkyNum, secNum), 'w') as f:
        json.dump(region_dict, f)
        f.close()

    # Now need to extract the region and create a deformation and image that have the same resolution as the img_region
    deform_sub = cc.SubVol(bfi_df, region_dict[region]['deformation_bbx'],
                           region_dict[region]['deformation_bby'])

    common.DebugHere()
    sizeout = [
        int(
            np.ceil((deform_sub.size().x * deform_sub.spacing().x) /
                    img_region.spacing().x)),
        int(
            np.ceil((deform_sub.size().y * deform_sub.spacing().y) /
                    img_region.spacing().y)), 1
    ]

    region_grid = cc.MakeGrid(sizeout,
                              img_region.spacing().tolist(),
                              deform_sub.origin().tolist())

    def_im_region = ca.Image3D(region_grid, deform_sub.memType())
    up_deformation = ca.Field3D(region_grid, deform_sub.memType())

    img_region.toType(ca.MEM_DEVICE)
    cc.ResampleWorld(up_deformation, deform_sub,
                     ca.BACKGROUND_STRATEGY_PARTIAL_ZERO)
    cc.ApplyHReal(def_im_region, img_region, up_deformation)

    ss_out = ss_dir + 'Blockface_registered/M{0}/section_{1}/{2}/'.format(
        mkyNum, secNum, region)

    if not pth.exists(pth.expanduser(ss_out)):
        os.mkdir(pth.expanduser(ss_out))

    common.SaveITKImage(
        def_im_region,
        pth.expanduser(ss_out) +
        'M{0}_01_section_{1}_{2}_def_to_bfi.nrrd'.format(
            mkyNum, secNum, region))
    common.SaveITKImage(
        def_im_region,
        pth.expanduser(ss_out) +
        'M{0}_01_section_{1}_{2}_def_to_bfi.tiff'.format(
            mkyNum, secNum, region))
    del img_region, def_im_region, ssiSrc, deform_sub

    # Now apply the same deformation to the confocal images
    conf_grid = cc.LoadGrid(
        conf_dir +
        'sidelight_registered/M{0}/section_{1}/{2}/affine_registration_grid.txt'
        .format(mkyNum, secNum, region))
    cf_out = conf_dir + 'blockface_registered/M{0}/section_{1}/{2}/'.format(
        mkyNum, secNum, region)
    # confocal.toType(ca.MEM_DEVICE)
    # def_conf = ca.Image3D(region_grid, deform_sub.memType())
    # cc.ApplyHReal(def_conf, confocal, up_deformation)

    for channel in range(0, 4):
        z_stack = []
        num_slices = len(
            glob.glob(conf_dir +
                      'sidelight_registered/M{0}/section_{1}/{3}/Ch{2}/*.tiff'.
                      format(mkyNum, secNum, channel, region)))
        for z in range(0, num_slices):
            src_im = common.LoadITKImage(
                conf_dir +
                'sidelight_registered/M{0}/section_{1}/{3}/Ch{2}/M{0}_01_section_{1}_LGN_RHS_Ch{2}_conf_aff_sidelight_z{4}.tiff'
                .format(mkyNum, secNum, channel, region,
                        str(z).zfill(2)))
            src_im.setGrid(
                cc.MakeGrid(
                    ca.Vec3Di(conf_grid.size().x,
                              conf_grid.size().y, 1), conf_grid.spacing(),
                    conf_grid.origin()))
            src_im.toType(ca.MEM_DEVICE)
            def_im = ca.Image3D(region_grid, ca.MEM_DEVICE)
            cc.ApplyHReal(def_im, src_im, up_deformation)
            def_im.toType(ca.MEM_HOST)
            common.SaveITKImage(
                def_im, cf_out +
                'Ch{2}/M{0}_01_section_{1}_{3}_Ch{2}_conf_def_blockface_z{4}.tiff'
                .format(mkyNum, secNum, channel, region,
                        str(z).zfill(2)))
            if z == 0:
                common.SaveITKImage(
                    def_im, cf_out +
                    'Ch{2}/M{0}_01_section_{1}_{3}_Ch{2}_conf_def_blockface_z{4}.nrrd'
                    .format(mkyNum, secNum, channel, region,
                            str(z).zfill(2)))
            z_stack.append(def_im)
            print('==> Done with Ch {0}: {1}/{2}'.format(
                channel, z, num_slices - 1))
        stacked = cc.Imlist_to_Im(z_stack)
        stacked.setSpacing(
            ca.Vec3Df(region_grid.spacing().x,
                      region_grid.spacing().y,
                      conf_grid.spacing().z))
        common.SaveITKImage(
            stacked, cf_out +
            'Ch{2}/M{0}_01_section_{1}_{3}_Ch{2}_conf_def_blockface_stack.nrrd'
            .format(mkyNum, secNum, channel, region))
        if channel == 0:
            cc.WriteGrid(
                stacked.grid(),
                cf_out + 'deformed_registration_grid.txt'.format(
                    mkyNum, secNum, region))