Esempio n. 1
0
    #Apply the deformation to all of the DW images
    ####[ca.ApplyH(def_list[x],scanList[x],Ephi) for x in scanVec]

    # Check for the sub directories and if they don't exist, make them
    if not os.path.exists(outdir + 'DWI_scan_{}'.format(num)):
        os.makedirs(outdir + 'DWI_scan_{}'.format(num))
    if not os.path.exists(outdir +
                          'DWI_scan_{}/individual_volumes'.format(num)):
        os.makedirs(outdir + 'DWI_scan_{}/individual_volumes'.format(num))
    if not os.path.exists(outdir +
                          'DWI_scan_{}/individual_volumes/MHA'.format(num)):
        os.makedirs(outdir + 'DWI_scan_{}/individual_volumes/MHA'.format(num))
    if not os.path.exists(outdir +
                          'DWI_scan_{}/individual_volumes/NIFTI'.format(num)):
        os.makedirs(outdir +
                    'DWI_scan_{}/individual_volumes/NIFTI'.format(num))

#    [cc.WriteMHA(def_list[x],outdir + 'T2_registered_scan{0}_direction{1}.mha'.format(num,str(x).zfill(2))) for x in scanVec]

####
    [
        cc.WriteMHA(
            scanList[x], outdir +
            'DWI_scan_{0}/individual_volumes/MHA/non-registered_scan{0}_direction{1}.mha'
            .format(num,
                    str(x).zfill(2))) for x in scanVec
    ]

    total_dirs += scanCount
if MRI_to_BFI:
    ca.ThreadMemoryManager.init(BFIgrid, mType, 6)
    spline = SolveSpline(TPS_landmarks)
    h = SplineToHField(spline, BFIgrid, mType)
    print ca.MinMax(h)
    MRIdef = ca.ManagedImage3D(BFIgrid, mType)
    #MRI = cc.LoadMHA(MRI_fname, mType)
    cc.ApplyHReal(MRIdef, MRI, h)

    # write data
    fname = 'MRI_TPS_to_block{0}.mha'.format(block)
    cd.Disp3Pane(MRIdef)
    print "Writing", outdir+fname
    if Write:
        cc.WriteMHA(MRIdef, outdir + fname)
    del MRIdef, MRI, h
    cc.MemInfo()


if BFI_to_MRI:
    TPS_landmarks = [[lmpair[1], lmpair[0]] for lmpair in TPS_landmarks]  # reverse
    spline = apps.SolveSpline(TPS_landmarks)  # only do once, b/c real coords#
    print spline
    #np.save(spline, outdir + 'block{0}_TPS_Spline_{1}.mha'.format(block,MRIsizes))
    for sz in MRIsizes:
        print "for size", sz
        # ca.ThreadMemoryManager.destroy()
        # MRIgrid = cc.MakeGrid([sz, sz, sz], [256.0/sz, 256.0/sz, 256.0/sz], 'center')
        # ca.ThreadMemoryManager.init(MRIgrid, mType, 6)
        
Esempio n. 3
0
                  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,
                    dir_save + 'BFI_block_' + str(block) + '_ve.mha')
    if SaveRGB:
        print 'Writing RGB'
        cc.WriteMHA(BFIDef3D_RGB,
                    dir_save + 'BFI_block_' + str(block) + '_rgb.mha')
    if SaveBW:
        cc.WriteMHA(BFIDef3D_BW,
                    dir_save + 'BFI_block_' + str(block) + '_bw.mha')

if not SaveInMRICoords:
    sys.exit()

# Save HD version of the blockface in MRI Coordinates
print 'saving blockface in blockface coords...'
mType = ca.MEM_HOST
import Affine_transforms
Esempio n. 4
0
    print ca.MinMax(weights)

    ca.Div_I(blocks, weights)

else:  # best
    imagedir = '/home/sci/crottman/korenberg/results/'
    blocks = cc.LoadMHA(
        imagedir + 'BFI_2D_Reg/block1_as_MRI_' + col + '_256.mha', ca.MEM_HOST)
    blk = cc.LoadMHA(imagedir + 'BFI_2D_Reg/block2_as_MRI_' + col + '_256.mha',
                     ca.MEM_HOST)
    blocks += blk
    blk = cc.LoadMHA(imagedir + 'landmark/block3_as_MRI_' + col + '.mha',
                     ca.MEM_HOST)
    blocks += blk
    blk = cc.LoadMHA(imagedir + 'landmark/block4_as_MRI_' + col + '.mha',
                     ca.MEM_HOST)
    blocks += blk
    imagedir = '/home/sci/crottman/korenberg/results/best/'

# Save Blocks

maxval = ca.MinMax(blocks)[1]

blocks /= maxval

fname_out = imagedir + 'blocks' + fname_end
cc.WriteMHA(blocks, fname_out)
if col == 'rgb':
    fname_out = imagedir + 'blocks_as_MRI_rgba_' + str(sz) + '.mha'
    cc.WriteColorMHA(blocks, fname_out)
Esempio n. 5
0
# tempDef = ca.Field3D(phi.grid(), memT)
totDef = ca.Field3D(phi.grid(), memT)
ca.ComposeHH(totDef, phi, Iphi, ca.BACKGROUND_STRATEGY_CLAMP)
# ca.ComposeHH(totDef, h, tempDef, ca.BACKGROUND_STRATEGY_CLAMP)

#Apply the deformation to the TPS live volume and rotate to the original volume
live_T2reg_rot = T2.copy()
cc.HtoReal(totDef)
cc.ApplyHReal(live_T2reg_rot, liveDef, totDef)
cd.Disp3Pane(live_T2reg_rot)
# live_T2reg = T2.copy()
# cc.ApplyAffineReal(live_T2reg,live_T2reg_rot,np.linalg.inv(rotMat))
# cd.Disp3Pane(live_T2reg)

if write:
    cc.WriteMHA(live_T2reg_rot,
                SaveDir + 'M13_01_live_as_MRI_full_bw_256_roty-119_flipy.mha')
    cc.WriteMHA(live_T2reg, SaveDir + 'M13_01_live_as_MRI_full_bw_256.mha')
    cc.WriteMHA(totDef,
                SaveDir + 'M13_01_live_to_MRI_roty-119_flipy_full_256.mha')
    paramDict = {}
    paramDict['Number of Itterations ER: '] = EnIter
    paramDict['Sigma ER: '] = Esigma
    paramDict['Step Size ER: '] = Eeps
    paramDict['Fluid Parameters ER: '] = Efp
    paramDict['Number of Itterations ID: '] = InIter
    paramDict['Sigma ID: '] = Isigma
    paramDict['Step Size ID: '] = Ieps
    with open(SaveDir + 'M13_01_live_to_MRI_reg_param.txt', 'w') as f:
        w = csv.writer(f)
        w.writerows(paramDict.items())
def main():
    # Extract the Monkey number and section number from the command line
    global frgNum
    global secOb

    mkyNum = sys.argv[1]
    secNum = sys.argv[2]
    frgNum = int(sys.argv[3])
    write = True

    # if not os.path.exists(os.path.expanduser('~/korenbergNAS/3D_database/Working/configuration_files/SidescapeRelateBlockface/M{0}/section_{1}/include_configFile.yaml'.format(mkyNum,secNum))):
    #     cf = initial(secNum, mkyNum)

    try:
        secOb = Config.Load(
            secSpec,
            pth.expanduser(
                '~/korenbergNAS/3D_database/Working/configuration_files/SidescapeRelateBlockface/M{0}/section_{1}/include_configFile.yaml'
                .format(mkyNum, secNum)))
    except IOError as e:
        try:
            temp = Config.LoadYAMLDict(pth.expanduser(
                '~/korenbergNAS/3D_database/Working/configuration_files/SidescapeRelateBlockface/M{0}/section_{1}/include_configFile.yaml'
                .format(mkyNum, secNum)),
                                       include=False)
            secOb = Config.MkConfig(temp, secSpec)
        except IOError:
            print 'It appears there is no configuration file for this section. Please initialize one and restart.'
            sys.exit()
        if frgNum == int(secOb.yamlList[frgNum][-6]):
            Fragmenter()
            try:
                secOb = Config.Load(
                    secSpec,
                    pth.expanduser(
                        '~/korenbergNAS/3D_database/Working/configuration_files/SidescapeRelateBlockface/M{0}/section_{1}/include_configFile.yaml'
                        .format(mkyNum, secNum)))
            except IOError:
                print 'It appeas that the include yaml file list does not match your fragmentation number. Please check them and restart.'
                sys.exit()

    if not pth.exists(
            pth.expanduser(secOb.ssiOutPath + 'frag{0}'.format(frgNum))):
        common.Mkdir_p(
            pth.expanduser(secOb.ssiOutPath + 'frag{0}'.format(frgNum)))
    if not pth.exists(
            pth.expanduser(secOb.bfiOutPath + 'frag{0}'.format(frgNum))):
        common.Mkdir_p(
            pth.expanduser(secOb.bfiOutPath + 'frag{0}'.format(frgNum)))
    if not pth.exists(
            pth.expanduser(secOb.ssiSrcPath + 'frag{0}'.format(frgNum))):
        os.mkdir(pth.expanduser(secOb.ssiSrcPath + 'frag{0}'.format(frgNum)))
    if not pth.exists(
            pth.expanduser(secOb.bfiSrcPath + 'frag{0}'.format(frgNum))):
        os.mkdir(pth.expanduser(secOb.bfiSrcPath + 'frag{0}'.format(frgNum)))

    frgOb = Config.MkConfig(secOb.yamlList[frgNum], frgSpec)
    ssiSrc, bfiSrc, ssiMsk, bfiMsk = Loader(frgOb, ca.MEM_HOST)

    #Extract the saturation Image from the color iamge
    bfiHsv = common.FieldFromNPArr(
        matplotlib.colors.rgb_to_hsv(
            np.rollaxis(np.array(np.squeeze(bfiSrc.asnp())), 0, 3)),
        ca.MEM_HOST)
    bfiHsv.setGrid(bfiSrc.grid())
    bfiSat = ca.Image3D(bfiSrc.grid(), bfiHsv.memType())
    ca.Copy(bfiSat, bfiHsv, 1)
    #Histogram equalize, normalize and mask the blockface saturation image
    bfiSat = cb.HistogramEqualize(bfiSat, 256)
    bfiSat.setGrid(bfiSrc.grid())
    bfiSat *= -1
    bfiSat -= ca.Min(bfiSat)
    bfiSat /= ca.Max(bfiSat)
    bfiSat *= bfiMsk
    bfiSat.setGrid(bfiSrc.grid())

    #Write out the blockface region after adjusting the colors with a format that supports header information
    if write:
        common.SaveITKImage(
            bfiSat,
            pth.expanduser(secOb.bfiSrcPath +
                           'frag{0}/M{1}_01_bfi_section_{2}_frag{0}_sat.nrrd'.
                           format(frgNum, secOb.mkyNum, secOb.secNum)))

    #Set the sidescape grid relative to that of the blockface
    ssiSrc.setGrid(ConvertGrid(ssiSrc.grid(), bfiSat.grid()))
    ssiMsk.setGrid(ConvertGrid(ssiMsk.grid(), bfiSat.grid()))
    ssiSrc *= ssiMsk

    #Write out the sidescape masked image in a format that stores the header information
    if write:
        common.SaveITKImage(
            ssiSrc,
            pth.expanduser(secOb.ssiSrcPath +
                           'frag{0}/M{1}_01_ssi_section_{2}_frag{0}.nrrd'.
                           format(frgNum, secOb.mkyNum, secOb.secNum)))

    #Update the image parameters of the sidescape image for future use
    frgOb.imSize = ssiSrc.size().tolist()
    frgOb.imOrig = ssiSrc.origin().tolist()
    frgOb.imSpac = ssiSrc.spacing().tolist()
    updateFragOb(frgOb)

    #Find the affine transform between the two fragments
    bfiAff, ssiAff, aff = Affine(bfiSat, ssiSrc, frgOb)
    updateFragOb(frgOb)

    #Write out the affine transformed images in a format that stores header information
    if write:
        common.SaveITKImage(
            bfiAff,
            pth.expanduser(
                secOb.bfiOutPath +
                'frag{0}/M{1}_01_bfi_section_{2}_frag{0}_aff_ssi.nrrd'.format(
                    frgNum, secOb.mkyNum, secOb.secNum)))
        common.SaveITKImage(
            ssiAff,
            pth.expanduser(
                secOb.ssiOutPath +
                'frag{0}/M{1}_01_ssi_section_{2}_frag{0}_aff_bfi.nrrd'.format(
                    frgNum, secOb.mkyNum, secOb.secNum)))

    bfiVe = bfiAff.copy()
    ssiVe = ssiSrc.copy()
    cc.VarianceEqualize_I(bfiVe, sigma=frgOb.sigVarBfi, eps=frgOb.epsVar)
    cc.VarianceEqualize_I(ssiVe, sigma=frgOb.sigVarSsi, eps=frgOb.epsVar)

    #As of right now, the largest pre-computed FFT table is 2048, so resample onto that grid for registration
    regGrd = ConvertGrid(
        cc.MakeGrid(ca.Vec3Di(2048, 2048, 1), ca.Vec3Df(1, 1, 1),
                    ca.Vec3Df(0, 0, 0)), ssiSrc.grid())
    ssiReg = ca.Image3D(regGrd, ca.MEM_HOST)
    bfiReg = ca.Image3D(regGrd, ca.MEM_HOST)
    cc.ResampleWorld(ssiReg, ssiVe)
    cc.ResampleWorld(bfiReg, bfiVe)

    #Create the default configuration object for IDiff Matching and then set some parameters
    idCf = Config.SpecToConfig(IDiff.Matching.MatchingConfigSpec)
    idCf.compute.useCUDA = True
    idCf.io.outputPrefix = '/home/sci/blakez/IDtest/'

    #Run the registration
    ssiDef, phi = DefReg(ssiReg, bfiReg, frgOb, ca.MEM_DEVICE, idCf)

    #Turn the deformation into a displacement field so it can be applied to the large tif with C++ code
    affV = phi.copy()
    cc.ApplyAffineReal(affV, phi, np.linalg.inv(frgOb.affine))
    ca.HtoV_I(affV)

    #Apply the found deformation to the input ssi
    ssiSrc.toType(ca.MEM_DEVICE)
    cc.HtoReal(phi)
    affPhi = phi.copy()
    ssiBfi = ssiSrc.copy()
    upPhi = ca.Field3D(ssiSrc.grid(), phi.memType())

    cc.ApplyAffineReal(affPhi, phi, np.linalg.inv(frgOb.affine))
    cc.ResampleWorld(upPhi, affPhi, bg=2)
    cc.ApplyHReal(ssiBfi, ssiSrc, upPhi)

    # ssiPhi = ca.Image3D(ssiSrc.grid(), phi.memType())
    # upPhi = ca.Field3D(ssiSrc.grid(), phi.memType())
    # cc.ResampleWorld(upPhi, phi, bg=2)
    # cc.ApplyHReal(ssiPhi, ssiSrc, upPhi)
    # ssiBfi = ssiSrc.copy()
    # cc.ApplyAffineReal(ssiBfi, ssiPhi, np.linalg.inv(frgOb.affine))

    # #Apply affine to the deformation
    # affPhi = phi.copy()
    # cc.ApplyAffineReal(affPhi, phi, np.linalg.inv(frgOb.affine))

    if write:
        common.SaveITKImage(
            ssiBfi,
            pth.expanduser(
                secOb.ssiOutPath +
                'frag{0}/M{1}_01_ssi_section_{2}_frag{0}_def_bfi.nrrd'.format(
                    frgNum, secOb.mkyNum, secOb.secNum)))
        cc.WriteMHA(
            affPhi,
            pth.expanduser(
                secOb.ssiOutPath +
                'frag{0}/M{1}_01_ssi_section_{2}_frag{0}_to_bfi_real.mha'.
                format(frgNum, secOb.mkyNum, secOb.secNum)))
        cc.WriteMHA(
            affV,
            pth.expanduser(
                secOb.ssiOutPath +
                'frag{0}/M{1}_01_ssi_section_{2}_frag{0}_to_bfi_disp.mha'.
                format(frgNum, secOb.mkyNum, secOb.secNum)))

    #Create the list of names that the deformation should be applied to
    # nameList = ['M15_01_0956_SideLight_DimLED_10x_ORG.tif',
    #             'M15_01_0956_TyrosineHydroxylase_Ben_10x_Stitching_c1_ORG.tif',
    #             'M15_01_0956_TyrosineHydroxylase_Ben_10x_Stitching_c2_ORG.tif',
    #             'M15_01_0956_TyrosineHydroxylase_Ben_10x_Stitching_c3_ORG.tif']

    # appLarge(nameList, affPhi)

    common.DebugHere()
Esempio n. 7
0
aff = apps.SolveAffine(landmarks)

with open(M13dir + 'TPS/M13_01_TPSLandmarks_5.txt', 'r') as m13:
    TPS13 = [[float(v) for v in line.split()] for line in m13]

with open(M15dir + 'TPS/M15_01_TPSLandmarks_5.txt', 'r') as m15:
    TPS15 = [[float(v) for v in line.split()] for line in m15]

if M15_to_M13:
    write = True

    def_aff = ca.Image3D(M13_aff.grid(), memT)
    cc.ApplyAffineReal(def_aff, M15, np.linalg.inv(aff))

    if write:
        cc.WriteMHA(def_aff, M15dir + 'Affine/M15_01_MRI_affine_to_M13.mha')
        np.save(M15dir + 'Affine/M15_01_MRI_affMat_to_M13.npy',
                np.linalg.inv(aff))

    landmarks = [[TPS13[x], TPS15[x]] for x in range(0, np.shape(TPS15)[0])]

    # Convert to real coordinates
    for lm in landmarks:
        lm[0] = np.ndarray.tolist(
            np.multiply(lm[0],
                        M13_aff.spacing().tolist()) +
            M13_aff.origin().tolist())
        lm[1] = np.ndarray.tolist(
            np.multiply(lm[1],
                        M13_aff.spacing().tolist()) +
            M13_aff.origin().tolist())