def Affine(I_src, I_tar, cfOb):
    '''Function for finding and applyiing the affine between two image fragments, I_src and I_tar. Returns both images with the affine applied and the affine trasform'''

    if cfOb.affine == 'None':
        landmarks = pp.LandmarkPicker(
            [np.squeeze(I_src.asnp()),
             np.squeeze(I_tar.asnp())])  #will be forward from BFI to SSI
        for lm in landmarks:
            lm[0] = np.ndarray.tolist(
                np.multiply(lm[0],
                            I_src.spacing().tolist()[0:2]) +
                I_src.origin().tolist()[0:2])
            lm[1] = np.ndarray.tolist(
                np.multiply(lm[1],
                            I_tar.spacing().tolist()[0:2]) +
                I_tar.origin().tolist()[0:2])
        aff = apps.SolveAffine(landmarks)
        cfOb.affine = aff.tolist()

    I_src_aff = I_tar.copy()
    I_tar_aff = I_src.copy()

    cc.ApplyAffineReal(I_src_aff, I_src, cfOb.affine)
    cc.ApplyAffineReal(I_tar_aff, I_tar, np.linalg.inv(np.array(cfOb.affine)))

    return I_src_aff, I_tar_aff, cfOb.affine
def SubRegion(src_grid, sub_grid, def_grid):
    # The sapcing of the src image was changed, so we have to find the new spacing of the sub region
    reg_grid = ConvertGrid(src_grid, def_grid)
    spacing = (np.array(reg_grid.spacing().tolist()) / np.array(
        src_grid.spacing().tolist())) * np.array(sub_grid.spacing().tolist())

    # Because we updated the spacing, the origin of the sub region will change and we have to find the new origin
    # The new origin is the upper left real coordinate of the subregion to extract
    pixel_origin = np.array(sub_grid.origin().tolist()) / np.array(
        src_grid.spacing().tolist())
    upL_real = pixel_origin * np.array(reg_grid.spacing().tolist()) + np.array(
        reg_grid.origin().tolist())

    # Now need to find the bottom right in real coordinates
    btR_real = (spacing * np.array(sub_grid.size().tolist())) + upL_real

    # Now that we have the top left and bottom right, we need to convert them to index corrdiantes of the deformation grid
    upL = np.floor((upL_real - np.array(def_grid.origin().tolist())) /
                   np.array(def_grid.spacing().tolist()))
    btR = np.floor((btR_real - np.array(def_grid.origin().tolist())) /
                   np.array(def_grid.spacing().tolist()))

    xrng = [int(upL[0]), int(btR[0])]
    yrng = [int(upL[1]), int(btR[1])]

    new_sub_grid = cc.MakeGrid(
        ca.Vec3Di(sub_grid.size()[0],
                  sub_grid.size()[1], 1), ca.Vec3Df(spacing[0], spacing[1], 1),
        ca.Vec3Df(upL_real[0], upL_real[1], 0))

    return xrng, yrng, new_sub_grid
def bb_grid_solver(source_image, affine):
    in_sz = source_image.size().tolist()
    in_sp = source_image.spacing().tolist()
    in_or = source_image.origin().tolist()

    C1temp = in_or[0:2]
    C1temp.append(1)
    C1 = C1temp
    C2 = np.array([in_sz[0] * in_sp[0] + in_or[0], in_or[1], 1])
    C3 = np.array([in_or[0], in_sz[1] * in_sp[1] + in_or[1], 1])
    C4 = np.array(
        [in_sz[0] * in_sp[0] + in_or[0], in_sz[1] * in_sp[1] + in_or[1], 1])

    corners = np.matrix([C1, C2, C3, C4])
    tCorners = affine * corners.transpose()

    bbMax = np.max(tCorners[:, 0:4], 1)
    bbMin = np.min(tCorners[:, 0:4], 1)

    dim = np.ceil(bbMax - bbMin)

    out_sp = (np.squeeze(np.array(dim)) / source_image.size()[0:3]
              )  # * (1/np.sqrt(2))
    if out_sp[2] == 0.0:
        out_sp[2] = 1.0
    out_sz = np.squeeze(np.array(dim)) / out_sp.transpose()
    out_or = np.squeeze(
        np.array(bbMin))  # Maybe needs to be the center of the image??

    grid = cc.MakeGrid(
        [np.int(np.ceil(out_sz[0])),
         np.int(np.ceil(out_sz[1])), 1], [out_sp[0], out_sp[1], 1],
        [out_or[0], out_or[1], 0])

    return grid
def ConvertGrid(I_src_grid, I_tar_grid):
    '''Given a source grid and target grid, returns a grid for the source that is in the world coordinates of the target grid'''
    nS = np.multiply(
        np.divide(I_tar_grid.size().tolist(),
                  [float(i) for i in I_src_grid.size().tolist()]),
        I_tar_grid.spacing().tolist())
    return cc.MakeGrid(I_src_grid.size(), ca.Vec3Df(nS[0], nS[1], nS[2]),
                       'center')
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))
示例#6
0
def show_files(filelist, sleeptime=.6):
    '''given a list of files, it shows all those images (Doesn't yet
    work for color images'''

    plt.figure()
    loadtimelist = []
    if type(filelist) is not list:
        filelist = [filelist]
    for i in xrange(len(filelist)):
        fname = filelist[i]
        t = time.time()
        name = fname[fname.rfind('/'):fname.rfind('.')]
        Im = cc.LoadTIFF(fname, ca.MEM_HOST)
        print name, i
        cd.DispImage(Im, newFig=False, title=name)
        p = Popen(['xsel', '-pi'], stdin=PIPE)
        p.communicate(input="'" + name + ".png'" + ',\n')
        loadtime = time.time() - t
        loadtimelist.append(loadtime)
        time.sleep(sleeptime)
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
示例#8
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
示例#9
0
#else:
#    dir_mri = '/home/sci/crottman/korenberg/results/landmark/'
dir_save = '/home/sci/blakez/results/elast_reg/block1_480/'

SaveInMRICoords = True
MRI_sz = [256]  # list of sizes
SaveInBFICoords = False

SaveRGB = False
SaveVE = False
SaveBW = True
SaveVF = False
debug = False

# load BFI slice and MRI_as_BFI slices
BFI3D = cc.LoadMHA(dir_bf + 'block' + str(block) + 'as_MRI_bw_256.mha',
                   ca.MEM_HOST)  # B/W
MRI3D = cc.LoadMHA(dir_mri + 'T2Seg.mha', ca.MEM_HOST)

# Initialize Deformed 3D Volumes
if SaveRGB:
    BFI_color3D = cc.LoadMHA(dir_bf + 'block' + str(block) + '_reg_rgb.mha',
                             ca.MEM_HOST)
    BFIDef3D_RGB = ca.Field3D(BFI3D.grid(), BFI3D.memType())
    ca.SetMem(BFIDef3D_RGB, 0.0)
if SaveVE:
    BFIDef3D_VE = ca.Image3D(BFI3D.grid(), BFI3D.memType())
    ca.SetMem(BFIDef3D_VE, 0.0)
if SaveBW:
    BFIDef3D_BW = ca.Image3D(BFI3D.grid(), BFI3D.memType())
    ca.SetMem(BFIDef3D_BW, 0.0)
if SaveVF:
示例#10
0
#############################

imagedir = '/home/sci/crottman/korenberg/results/' + reg_type + '/'
if reg_type in ['landmark', 've_reg']:
    fname_end = '_as_MRI_' + col + '.mha'
else:
    fname_end = '_as_MRI_' + col + '_' + str(sz) + '.mha'

if sz >= 512:
    mType = ca.MEM_HOST
else:
    mType = ca.MEM_DEVICE

if reg_type is not 'best':
    grid = cc.MakeGrid([sz, sz, sz], [256.0 / sz, 256.0 / sz, 256.0 / sz],
                       'center')
    blocks = ca.Field3D(grid, mType)
    ca.SetMem(blocks, 0.0)
    weights = blocks.copy()
    ca.SetMem(weights, 0.0)

    for i in xrange(1, 5):
        fname = imagedir + 'block' + str(i) + fname_end
        try:
            blk = cc.LoadMHA(fname, mType)
        except IOError:
            print 'Warning... block ' + str(i) + ' does not exist'
            continue
        blocks += blk
        weight3 = blk.copy()
        try:
示例#11
0
plt.ion()
plt.close('all')
import PyCA.Common as common
from PyCAApps import ElastReg
import matplotlib.mlab as mlab
import scipy
import matplotlib.patches as patches

memT = ca.MEM_DEVICE

conDir = '/local/blakez/Backup/M13_01/data/microscopy/confocal/M13_01_B2_43_S5/zslice_tiles_00/C02/'

#micDir = '/local/blakez/korenbergNAS/3D_database/Raw/Microscopic/Confocal/M13/M13-01-B2-10-S3/2016_10_13_17_45_10--M13-01-B2-10-S3 5x tiling/'
#micOut = '/home/sci/blakez/M13_01/results/microscopic/intensityCorrected/test/'

image = cc.LoadTIFF(conDir + 'M13-01-B2-43-S5-C2_Z0_tile_000.tif', memT)

stack = np.zeros((512, 512, 420), dtype='uint8')

for ii in range(0, 420):
    image = plt.imread(
        conDir +
        'M13-01-B2-43-S5-C2_Z0_tile_{0}.tif'.format(str(int(ii)).zfill(3)),
        memT)
    stack[:, :, ii] = image

fMask = (
    stack > 1
)  # Can Adjust what is considered background by changing the comparison number
f = stack * fMask
m = np.sum(f, axis=2, dtype='float') / np.sum(fMask, axis=2, dtype='float')
import PyCAApps as apps
import matplotlib
import scipy
import yaml
from scipy import ndimage

plt.ion()
plt.close('all')
import glob
import json
import sys
import gc
import os
import os.path as pth

cc.SelectGPU(2)


def load_and_solve(target_points_file, source_points_file):
    target_points = np.loadtxt(target_points_file, delimiter=' ')[:, 0:2]
    source_points = np.loadtxt(source_points_file, delimiter=' ')[:, 0:2]

    landmarks = []
    for pt in range(0, len(target_points)):
        landmarks.append(
            [source_points[pt].tolist(), target_points[pt].tolist()])

    return apps.SolveAffine(np.array(landmarks))


def ConvertGrid(I_src_grid, I_tar_grid):
示例#13
0
plt.close('all')
import PyCA.Common as common
from PyCAApps import ElastReg, SolveSpline, SplineToHField, DefPoint, IDiff

livedir = '/home/sci/blakez/M15-01/Data/MRI/liveMRI/'
# livedir = '/local/blakez/korenbergNAS/3D_database/Raw/MRI/in_vivo_MRI/M15/HARVEY_IN_VIVO/'
# T2dir = '/home/sci/blakez/M13_01/data/MRI/'
T2dir = '/home/sci/blakez/M15-01/Data/MRI/HARVEY_OSAMA_TOBLAKE/'
ex = 'Korenberg09_MonkeyBrain_Korenberg09_MonkeyBrain_081815_Live_Harv__E16_P1_2.16.756.5.5.100.1654368313.31476.1439925928.1/'
SaveDir = '/home/sci/blakez/M15-01/Results/MRI/invivo_MRI/081815_E16/'

memT = ca.MEM_DEVICE
write = False

# T2 = cc.LoadMHA(T2dir + 'T2Seg_roty-119_flipy.mha',memT)
T2 = cc.LoadMHA(T2dir + 'T2_MRI.mha', memT)
T2_mask = cc.LoadMHA(T2dir + '../M15_01_MRI_Full_Mask.mha', memT)
T2 *= T2_mask
# rotMat = np.load(T2dir + 'rotationMatrix.npy')
# live = cc.LoadMHA(livedir + 'M13_01_live_MRI.mha',memT)
live = cc.LoadMHA(livedir + 'M15_01_live_MRI_E16.mha', memT)
live_mask = cc.LoadNRRD(SaveDir + 'M15_01_live_MRI_mask.nrrd', memT)

live_mask.setOrigin(live.origin())
live -= ca.Min(live)
live /= ca.Max(live)
live *= live_mask

with open(SaveDir + 'M15_01_LiveE16-T2_Landmarks.json', 'r') as f:
    landmarks = json.load(f)
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()
def Fragmenter():
    tmpOb = Config.Load(
        frgSpec,
        pth.expanduser(
            '~/korenbergNAS/3D_database/Working/configuration_files/SidescapeRelateBlockface/M{0}/section_{1}/section_{1}_frag0.yaml'
            .format(secOb.mkyNum, secOb.secNum)))
    dictBuild = {}
    #Load in the whole image so that the fragment can cropped out
    ssiSrc, bfiSrc, ssiMsk, bfiMsk = Loader(tmpOb, ca.MEM_HOST)

    #Because some of the functions only woth with gray images
    bfiGry = ca.Image3D(bfiSrc.grid(), bfiSrc.memType())
    ca.Copy(bfiGry, bfiSrc, 1)

    lblSsi, _ = ndimage.label(np.squeeze(ssiMsk.asnp()) > 0)
    lblBfi, _ = ndimage.label(np.squeeze(bfiMsk.asnp()) > 0)

    seedPt = np.squeeze(pp.LandmarkPicker([lblBfi, lblSsi]))
    subMskBfi = common.ImFromNPArr(lblBfi == lblBfi[seedPt[0, 0],
                                                    seedPt[0,
                                                           1]].astype('int8'),
                                   sp=bfiSrc.spacing(),
                                   orig=bfiSrc.origin())
    subMskSsi = common.ImFromNPArr(lblSsi == lblSsi[seedPt[1, 0],
                                                    seedPt[1,
                                                           1]].astype('int8'),
                                   sp=ssiSrc.spacing(),
                                   orig=ssiSrc.origin())

    bfiGry *= subMskBfi
    bfiSrc *= subMskBfi
    ssiSrc *= subMskSsi
    #Pick points that are the bounding box of the desired subvolume
    corners = np.array(
        pp.LandmarkPicker(
            [np.squeeze(bfiGry.asnp()),
             np.squeeze(ssiSrc.asnp())]))
    bfiCds = corners[:, 0]
    ssiCds = corners[:, 1]

    #Extract the region from the source images
    bfiRgn = cc.SubVol(bfiSrc,
                       xrng=[bfiCds[0, 0], bfiCds[1, 0]],
                       yrng=[bfiCds[0, 1], bfiCds[1, 1]])
    ssiRgn = cc.SubVol(ssiSrc,
                       xrng=[ssiCds[0, 0], ssiCds[1, 0]],
                       yrng=[ssiCds[0, 1], ssiCds[1, 1]])

    #Extract the region from the mask images
    rgnMskSsi = cc.SubVol(subMskSsi,
                          xrng=[ssiCds[0, 0], ssiCds[1, 0]],
                          yrng=[ssiCds[0, 1], ssiCds[1, 1]])
    rgnMskBfi = cc.SubVol(subMskBfi,
                          xrng=[bfiCds[0, 0], bfiCds[1, 0]],
                          yrng=[bfiCds[0, 1], bfiCds[1, 1]])

    dictBuild['rgnBfi'] = np.divide(
        bfiCds, np.array(bfiSrc.size().tolist()[0:2], 'float')).tolist()
    dictBuild['rgnSsi'] = np.divide(
        ssiCds, np.array(ssiSrc.size().tolist()[0:2], 'float')).tolist()

    #Check the output directory for the source files of the fragment
    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)))
    #Check the output directory for the mask files of the fragment
    if not pth.exists(
            pth.expanduser(secOb.ssiMskPath + 'frag{0}'.format(frgNum))):
        os.mkdir(pth.expanduser(secOb.ssiMskPath + 'frag{0}'.format(frgNum)))
    if not pth.exists(
            pth.expanduser(secOb.bfiMskPath + 'frag{0}'.format(frgNum))):
        os.mkdir(pth.expanduser(secOb.bfiMskPath + 'frag{0}'.format(frgNum)))

    dictBuild[
        'ssiSrcName'] = 'frag{0}/M{1}_01_ssi_section_{2}_frag1.tif'.format(
            frgNum, secOb.mkyNum, secOb.secNum)
    dictBuild[
        'bfiSrcName'] = 'frag{0}/M{1}_01_bfi_section_{2}_frag1.mha'.format(
            frgNum, secOb.mkyNum, secOb.secNum)
    dictBuild[
        'ssiMskName'] = 'frag{0}/M{1}_01_ssi_section_{2}_frag1_mask.tif'.format(
            frgNum, secOb.mkyNum, secOb.secNum)
    dictBuild[
        'bfiMskName'] = 'frag{0}/M{1}_01_bfi_section_{2}_frag1_mask.tif'.format(
            frgNum, secOb.mkyNum, secOb.secNum)

    #Write out the masked and cropped images so that they can be loaded from the YAML file
    #The BFI region needs to be saved as color and mha format so that the grid information is carried over.
    common.SaveITKImage(
        ssiRgn, pth.expanduser(secOb.ssiSrcPath + dictBuild['ssiSrcName']))
    cc.WriteColorMHA(
        bfiRgn, pth.expanduser(secOb.bfiSrcPath + dictBuild['bfiSrcName']))
    common.SaveITKImage(
        rgnMskSsi, pth.expanduser(secOb.ssiMskPath + dictBuild['ssiMskName']))
    common.SaveITKImage(
        rgnMskBfi, pth.expanduser(secOb.bfiMskPath + dictBuild['bfiMskName']))

    frgOb = Config.MkConfig(dictBuild, frgSpec)
    updateFragOb(frgOb)

    return None
示例#16
0
def RigidReg(
    Is,
    It,
    theta_step=.0001,
    t_step=.01,
    a_step=0,
    maxIter=350,
    plot=True,
    origin=None,
    theta=0,  # only applies for 2D
    t=None,  # only applies for 2D
    Ain=np.matrix(np.identity(3))):

    Idef = ca.Image3D(It.grid(), It.memType())
    gradIdef = ca.Field3D(It.grid(), It.memType())
    h = ca.Field3D(It.grid(), It.memType())
    ca.SetToIdentity(h)
    x = ca.Image3D(It.grid(), It.memType())
    y = ca.Image3D(It.grid(), It.memType())
    DX = ca.Image3D(It.grid(), It.memType())
    DY = ca.Image3D(It.grid(), It.memType())
    diff = ca.Image3D(It.grid(), It.memType())
    scratchI = ca.Image3D(It.grid(), It.memType())

    ca.Copy(x, h, 0)
    ca.Copy(y, h, 1)
    if origin is None:
        origin = [(Is.grid().size().x + 1) / 2.0,
                  (Is.grid().size().y + 1) / 2.0,
                  (Is.grid().size().z + 1) / 2.0]
    x -= origin[0]
    y -= origin[1]

    numel = It.size().x * It.size().y * It.size().z
    immin, immax = ca.MinMax(It)
    imrng = max(immax - immin, .01)
    t_step /= numel * imrng
    theta_step /= numel * imrng
    a_step /= numel * imrng
    energy = []
    a = 1

    if cc.Is3D(Is):
        if theta:
            print "theta is not utilized in 3D registration"
        z = ca.Image3D(It.grid(), It.memType())
        DZ = ca.Image3D(It.grid(), It.memType())
        ca.Copy(z, h, 2)
        z -= origin[2]

        A = np.matrix(np.identity(4))
        cc.ApplyAffineReal(Idef, Is, A)
        #        cc.ApplyAffine(Idef, Is, A, origin)

        t = [0, 0, 0]
        for i in xrange(maxIter):
            ca.Sub(diff, Idef, It)
            ca.Gradient(gradIdef, Idef)
            ca.Copy(DX, gradIdef, 0)
            ca.Copy(DY, gradIdef, 1)
            ca.Copy(DZ, gradIdef, 2)

            # take gradient step for the translation
            ca.Mul(scratchI, DX, diff)
            t[0] += t_step * ca.Sum(scratchI)
            ca.Mul(scratchI, DY, diff)
            t[1] += t_step * ca.Sum(scratchI)
            ca.Mul(scratchI, DZ, diff)
            t[2] += t_step * ca.Sum(scratchI)

            A[0, 3] = t[0]
            A[1, 3] = t[1]
            A[2, 3] = t[2]
            if a_step > 0:
                DX *= x
                DY *= y
                DZ *= z
                DZ += DX
                DZ += DY
                DZ *= diff
                d_a = a_step * ca.Sum(DZ)
                a_prev = a
                a += d_a
                # multiplying by a/a_prev is equivalent to adding (a-aprev)
                A = A * np.matrix([[a / a_prev, 0, 0, 0], [
                    0, a / a_prev, 0, 0
                ], [0, 0, a / a_prev, 0], [0, 0, 0, 1]])

            # Z rotation
            ca.Copy(DX, gradIdef, 0)
            ca.Copy(DY, gradIdef, 1)
            DX *= y
            ca.Neg_I(DX)
            DY *= x
            ca.Add(scratchI, DX, DY)
            scratchI *= diff
            theta = -theta_step * ca.Sum(scratchI)
            # % Recalculate A
            A = A * np.matrix(
                [[np.cos(theta), np.sin(theta), 0, 0],
                 [-np.sin(theta), np.cos(theta), 0, 0], [0, 0, 1, 0],
                 [0, 0, 0, 1]])

            # Y rotation
            ca.Copy(DX, gradIdef, 0)
            ca.Copy(DZ, gradIdef, 2)
            DX *= z
            ca.Neg_I(DX)
            DZ *= x
            ca.Add(scratchI, DX, DZ)
            scratchI *= diff
            theta = -theta_step * ca.Sum(scratchI)
            # % Recalculate A
            A = A * np.matrix(
                [[np.cos(theta), 0, np.sin(theta), 0], [0, 1, 0, 0],
                 [-np.sin(theta), 0, np.cos(theta), 0], [0, 0, 0, 1]])

            # X rotation
            ca.Copy(DY, gradIdef, 1)
            ca.Copy(DZ, gradIdef, 2)
            DY *= z
            ca.Neg_I(DY)
            DZ *= y
            ca.Add(scratchI, DY, DZ)
            scratchI *= diff
            theta = -theta_step * ca.Sum(scratchI)
            # Recalculate A
            A = A * np.matrix(
                [[1, 0, 0, 0], [0, np.cos(theta),
                                np.sin(theta), 0],
                 [0, -np.sin(theta), np.cos(theta), 0], [0, 0, 0, 1]])

            cc.ApplyAffineReal(Idef, Is, A)
            #        cc.ApplyAffine(Idef, Is, A, origin)

            # % display Energy (and other figures) at the end
            energy.append(ca.Sum2(diff))
            if (i == maxIter -
                    1) or (i > 75 and abs(energy[-1] - energy[-50]) < immax):
                cd.DispImage(diff, title='Difference Image', colorbar=True)
                plt.figure()
                plt.plot(energy)
                cd.DispImage(Idef, title='Deformed Image')
                break

    elif cc.Is2D(Is):
        # theta = 0
        if t is None:
            t = [0, 0]

        # A = np.array([[a*np.cos(theta), np.sin(theta), t[0]],
        #               [-np.sin(theta), a*np.cos(theta), t[1]],
        #               [0, 0, 1]])

        A = np.copy(Ain)
        cc.ApplyAffineReal(Idef, Is, A)
        # ca.Copy(Idef, Is)
        for i in xrange(1, maxIter):
            # [FX,FY] = gradient(Idef)
            ca.Sub(diff, Idef, It)
            ca.Gradient(gradIdef, Idef)
            ca.Copy(DX, gradIdef, 0)
            ca.Copy(DY, gradIdef, 1)

            # take gradient step for the translation
            ca.Mul(scratchI, DX, diff)
            t[0] += t_step * ca.Sum(scratchI)
            ca.Mul(scratchI, DY, diff)
            t[1] += t_step * ca.Sum(scratchI)

            # take gradient step for the rotation theta
            if a_step > 0:
                # d/da
                DX *= x
                DY *= y
                DY += DX
                DY *= diff
                d_a = a_step * ca.Sum(DY)
                a += d_a
            # d/dtheta
            ca.Copy(DX, gradIdef, 0)
            ca.Copy(DY, gradIdef, 1)
            DX *= y
            ca.Neg_I(DX)
            DY *= x
            ca.Add(scratchI, DX, DY)
            scratchI *= diff
            d_theta = theta_step * ca.Sum(scratchI)
            theta -= d_theta

            # Recalculate A, Idef
            A = np.matrix([[a * np.cos(theta),
                            np.sin(theta), t[0]],
                           [-np.sin(theta), a * np.cos(theta), t[1]],
                           [0, 0, 1]])
            A = Ain * A

            cc.ApplyAffineReal(Idef, Is, A)
            #        cc.ApplyAffine(Idef, Is, A, origin)

            # % display Energy (and other figures) at the end
            energy.append(ca.Sum2(diff))
            if (i == maxIter -
                    1) or (i > 75 and abs(energy[-1] - energy[-50]) < immax):
                if i == maxIter - 1:
                    print "not converged in ", maxIter, " Iterations"
                if plot:
                    cd.DispImage(diff, title='Difference Image', colorbar=True)
                    plt.figure()
                    plt.plot(energy)
                    cd.DispImage(Idef, title='Deformed Image')
                break
    return A
示例#17
0
# for a in folderList:
#     print a

#Load in the T2 image and downsample it to the resolution of the DW images
####
T2_list = sorted(glob.glob(indir + 'T2DICOM_scan26/*'))
refIm = dicom.read_file(T2_list[0])
PixelDims = (int(refIm.Rows), int(refIm.Columns), len(T2_list))
# PixelSpacing = (0.5,0.5,0.5)
T2Array = np.zeros(PixelDims, dtype=refIm.pixel_array.dtype)
for filename in T2_list:
    ds = dicom.read_file(filename)
    T2Array[:, :, T2_list.index(filename)] = ds.pixel_array
T2MRI = common.ImFromNPArr(T2Array)
T2MRI.setGrid(cc.MakeGrid(T2MRI.grid().size(), 0.5))
T2MRI.toType(ca.MEM_DEVICE)

#Swap the axis of the images so they align with the gradient directions
T2MRI = cc.SwapAxes(T2MRI, 0, 1)
T2MRI = cc.SwapAxes(T2MRI, 0, 2)
T2MRI = cc.FlipDim(T2MRI, 2)
# T2MRI = cc.FlipDim(T2MRI,2)

DWIgrid = cc.MakeGrid([120, 144, 120], 0.5, [0, 0, 0])
down_T2 = ca.Image3D(DWIgrid, ca.MEM_DEVICE)
ca.Resample(down_T2, T2MRI)
####
#Display the list

# cc.WriteMHA(down_T2,outdir + 'Images/T2_downSample_to_DWImha')
示例#18
0
    # mType=ca.MEM_HOST
    mType = ca.MEM_DEVICE
    ds = 2
else:
    mType = ca.MEM_DEVICE
    ds = 1

plt.close('all')

# Rigid Reg parameters
theta_step = 0
t_step = 300
a_step = 0
maxIter = 2000

Imprev = cc.LoadTIFF(filelist[0], mType, ds)
origin = [(Imprev.grid().size().x+1)/2.0, # origin for Affine matrix
          (Imprev.grid().size().y+1)/2.0,
          (Imprev.grid().size().z+1)/2.0]
scratchI = ca.Image3D(Imprev.grid(), Imprev.memType())
scratchI2 = ca.Image3D(Imprev.grid(), Imprev.memType())

# initialize dictionary
Adict = {'origin': origin}
Adict[files.get_file_dist(filelist[0])] = np.identity(3)

# if 'block1' in filelist[0]:
# move first image in block 1
if block == 1:
    tcentx, tcenty = cc.CenterImage(Imprev)
    ca.Copy(scratchI, Imprev)
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))
示例#20
0
            str(sec).zfill(4)), ca.MEM_HOST)

    bfi_list.append(bfi_org)

    if sec == slicestart:
        inplane_grid = ssi_reg.grid()
        reg_list.append(ssi_reg)
        aff_list.append(ssi_aff)
        print "Registered Grid: "
        print ssi_reg.grid()
        print "Affine Grid: "
        print ssi_aff.grid()
        print "Added Section {0}".format(sec)
    else:
        stack_temp = ca.Image3D(inplane_grid, ca.MEM_HOST)
        cc.ResampleWorld(stack_temp, ssi_reg)
        reg_list.append(stack_temp)

        aff_list.append(ssi_aff)
        print "Added Section {0}".format(sec)

print 'Attempting to make volumes'
ssi_reg_vol = cc.Imlist_to_Im(reg_list)
ssi_aff_vol = cc.Imlist_to_Im(aff_list)
bfi_org_vol = cc.Imlist_to_Im(bfi_list)

ssi_reg_vol.setSpacing(
    ca.Vec3Df(ssi_reg_vol.spacing()[0],
              ssi_reg_vol.spacing()[1], 0.030))
ssi_aff_vol.setSpacing(
    ca.Vec3Df(ssi_aff_vol.spacing()[0],
示例#21
0
import PyCA.Core as ca
import numpy as np
import sys
import PyCACalebExtras.Common as cc
import PyCACalebExtras.Display as cd
import matplotlib.pyplot as plt
plt.close('all')

block = 3  # 1, 2, 3, 4

dir_in = '/home/sci/crottman/korenberg/results/landmark/'
dir_out = '/home/sci/crottman/korenberg/results/ve_reg/'

Imri = cc.LoadMHA('/home/sci/crottman/korenberg/results/MRI/brain_seg.mha')
cc.SetRegionLT(Imri, Imri, 1.0, 20000)
VEmri = ca.Image3D(Imri.grid(), Imri.memType())
cc.VarianceEqualize(VEmri, Imri, sigma=2.0)

# # load landmark registered blocks
# Ibfi = cc.LoadMHA(dir_in + 'block' + str(block) + '_as_MRI_bw.mha')
# ca.Neg_I(Ibfi)
# VEbfi = ca.Image3D(Imri.grid(), Imri.memType())
# cc.VarianceEqualize(VEbfi, Ibfi, sigma=2.0)
# cd.DispImage(VEbfi, ca.MinMax(VEmri))

# load landmark registered pre-VEd block
VEbfi = cc.LoadMHA(dir_in + 'block' + str(block) + '_as_MRI_ve.mha')
ca.Neg_I(VEbfi)
# cc.WritePNG(VEbfi, 'VEbfi_block' + str(block) + 'new.png', rng = [-2.8, 2.8])
# cd.DispImage(Ibfi)
示例#22
0
import PyCA.Core as ca
import PyCA.Common as common
import numpy as np
from PyCAApps import SolveSpline, SplineToHField
import sys
from BFI_reg_landmarks import get_new_landmarks
# import matplotlib.pyplot as plt
# cc.SelectGPU()
plt.ion()
plt.close('all')

BFIdir = '/home/sci/crottman/korenberg/results/blockface/'
MRIdir = '/home/sci/crottman/korenberg/data/MRI/'

for block in [1, 2, 3, 4]:
    grid = cc.LoadGrid(BFIdir + 'block{0}_grid.txt'.format(block))
    sz = grid.size().tolist()
    sp = grid.spacing().tolist()
    o = grid.origin().tolist()
    print 'block' + str(block), 'size:', sz
    print 'block'+str(block), 'bound:', \
        o, 'to', [(sz[0]-1)*sp[0]+o[0],
                  (sz[1]-1)*sp[1]+o[1],
                  (sz[2]-1)*sp[2]+o[2]]

grid = cc.LoadGrid(MRIdir + 'T2_grid.txt'.format(block))
sz = grid.size().tolist()
sp = grid.spacing().tolist()
o = grid.origin().tolist()
print 'MRI size:', sz
print 'MRI bound:', \
示例#23
0
MRIdir = '/home/sci/blakez/M15-01/Data/MRI/HARVEY_OSAMA_TOBLAKE/'
MRI_fname = MRIdir + 'T2_MRI.mha'
BFIdir = '/local/blakez/korenbergNAS/3D_database/Working/Blockface/self_registered/M15/'
outdir = '/local/blakez/korenbergNAS/3D_database/Working/Blockface/T2_registered/Thin_plate_spline/M15/'

# for block in [1, 2, 3, 4]:
#     fname = 'block{0}_reg_fillblanks_bw.mha'.format(block)
#     tmp = cc.LoadMHA(BFIdir + fname)
#     cc.WriteGrid(tmp.grid(), BFIdir + 'block{0}_grid.txt'.format(block))
# tmp = cc.LoadMHA(MRI_fname)
# cc.WriteGrid(tmp.grid(), MRIdir + 'T2_grid.txt'.format(block))
# sys.exit()

#BFIgrid = cc.LoadGrid(BFIdir + 'block{0}_grid.txt'.format(block))
#MRIgrid = cc.LoadGrid(MRIdir + 'T2_grid.txt'.format(block))
MRI = cc.LoadMHA(MRI_fname,ca.MEM_HOST)
MRIgrid = MRI.grid()
#MRIgrid = cc.MakeGrid(MRI.size(),MRI.spacing(),'center')
#MRI.setGrid(MRIgrid)
#BFI = cc.LoadMHA(BFIdir + 'M15_01_seg_crop_hd8.mha',ca.MEM_HOST)
BFI_full = cc.LoadMHA(BFIdir + 'M15_01_hd8_VE.mha',ca.MEM_HOST)
BFI = cc.SubVol(BFI_full, yrng=[146,626])
BFIgrid = cc.MakeGrid(ca.Vec3Di(480,480,2239),ca.Vec3Df(0.1185,0.1185,0.030),'center')
BFI.setGrid(BFIgrid)
#BFIgrid = BFI.grid()
print MRIgrid
print BFIgrid
# print 'b4 memory', 480*480*874*4/1024./1024 *7  # 7 blocks, mem size
# print 'mri memory', 256*256*256*4/1024./1024 *7  # 7 blocks, mem size
# print 'mri big memory', 512*512*512*4/1024./1024 *7  # 7 blocks, mem size
# print 'single mri ', 256*256*256*4/1024./1024
示例#24
0
    '~/korenbergNAS/3D_database/Working/MRI/Post-Mortem_MRI/Subject_to_Subject/M13/'
)
M15dir = os.path.expanduser(
    '~/korenbergNAS/3D_database/Working/MRI/Post-Mortem_MRI/Subject_to_Subject/M15/'
)

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

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

aff_M13 = np.load(M13dir + 'Affine/rotationMatrix.npy')

M13_aff = cc.LoadMHA(M13dir + 'Affine/T2Seg_roty-119_flipy.mha', memT)
M15 = cc.LoadMHA(M15dir + 'Affine/T2_MRI.mha', memT)
M15_mask = cc.LoadNRRD(
    M15dir + 'Affine/M15_01_MRI_Full_Mask_lessBrainStem.nrrd', memT)
M13_mask = cc.LoadNRRD(
    M13dir + 'Affine/M13_01_MRI_Full_Mask_lessBrainStem.nrrd', memT)

M15_mask.setGrid(M15.grid())
M13_mask.setGrid(M13_aff.grid())

M15 *= M15_mask
M13_aff *= M13_mask

# Points in the M15 were chosen in Flipped Y coordiante system, so flip them back
# for pts in m15pts:
#     pts[0]= 256-pts[0]