Beispiel #1
0
# reading transforms from the low-resolution montage
IJ.log('reading the affine transform parameters from the affine montage')
transformsPath = os.path.join(MagC_EM_Folder, 'assembly_lowEM_Transforms.txt')
with (open(transformsPath, 'r')) as f:
	transforms = f.readlines()
nLayers = max([int(transforms[i]) for i in range(1, len(transforms),8) ]) + 1 # why not, could simply read the EM_Metadata parameters ...

# getting downsamplingFactor
downsamplingFactor = MagCParameters['downsample_EM']['downsamplingFactor']
factorString = str(int(1000000*downsamplingFactor)).zfill(8)

# create the normal resolution project
IJ.log('Creating project with the full size EM images')
projectPath = fc.cleanLinuxPath(os.path.join(MagC_EM_Folder,'EMProject.xml'))
project, loader, layerset, _ = fc.getProjectUtils(fc.initTrakem(fc.cleanLinuxPath(os.path.dirname(projectPath)), 1))
project.saveAs(projectPath, True)

# Assembling all images in the project with the transforms computed on the low res and adjusted with the scale factor
IJ.log('Assembling all images in the project with the transforms computed on the low res and adjusted with the scale factor')
paths = []
locations = []
layers = []
for i in range(0, len(transforms), 8):
	alignedPatchPath = transforms[i]
	alignedPatchName = os.path.basename(alignedPatchPath)
	toAlignPatchName = alignedPatchName.replace('_' + factorString, '').replace('_resized', '')
	toAlignPatchPath = os.path.join(MagCFolder, 'EMData', os.path.basename(os.path.dirname(alignedPatchPath)), toAlignPatchName)
	toAlignPatchPath = fc.cleanLinuxPath(toAlignPatchPath[:-1])  # mysterious trailing character ...
	IJ.log('toAlignPatchPath ' + toAlignPatchPath)
	l = int(transforms[i+1])
Beispiel #2
0
width, height, nChannels, xGrid, yGrid, scaleX, scaleY, channels = fc.readSessionMetadata(
    MagCFolder)

MagCParameters = fc.readMagCParameters(MagCFolder)
scaleFactors = MagCParameters[namePlugin][
    'scaleFactors']  # scale factor for export, typically 1 and 0.1
flipX = MagCParameters[namePlugin]['flipX']

IJ.log('Iterating over the LM channels')
for channel in channels:
    IJ.log('Processing channel ' + str(channel))
    IJ.log('Creating a TrakEM project')

    # create trakem project for the channel
    trakemFolder = os.path.join(os.path.dirname(transformsPath), '')
    project = fc.initTrakem(trakemFolder, nLayers)
    loader = project.getLoader()
    loader.setMipMapsRegeneration(False)  # disable mipmaps
    layerset = project.getRootLayerSet()

    # insert the tiles according to the transforms computed on the reference brightfield channel
    IJ.log('Inserting all patches')
    for i in range(0, len(transforms), 8):
        alignedPatchPath = transforms[i]
        l = int(transforms[i + 1])
        alignedPatchName = os.path.basename(alignedPatchPath)

        toAlignPatchPath = fc.cleanLinuxPath(
            os.path.join(os.path.dirname(alignedPatchPath),
                         alignedPatchName.replace(channels[-1], channel)))
        toAlignPatchPath = toAlignPatchPath[:
Beispiel #3
0
        lines[idLine] = 'channels = [' + ','.join(
            map(lambda x: "'" + x + "'", channels)) + ']'
f.close()
f = open(LMMetadataPath, 'w')
for line in lines:
    f.write(line + '\n')
f.close()
IJ.log('addContrastedChannel done')

# Create LM project with the contrastedChannel
nLayers = len(next(os.walk(LMDataFolder))[1])
IJ.log('nLayers is ' + str(nLayers))
IJ.log('Creating trakem project "LMProject" ')

project, loader, layerset, nLayers = fc.getProjectUtils(
    fc.initTrakem(LMFolder, nLayers))
projectPath = os.path.join(os.path.normpath(LMFolder), 'LMProject.xml')
project.saveAs(projectPath, True)

# determining tiles locations taking into account the overlap
paths, locations, layers = [], [], []
widthEffective = int((1 - overlap) * width)
heightEffective = int((1 - overlap) * height)

for channel in [contrastedChannel]:
    IJ.log('Assembling LM sections from all layers')
    for l in range(nLayers):
        IJ.log('Each section consists of ' + str(xGrid) + ' x ' + str(yGrid) +
               ' patches')
        for y in range(yGrid):
            for x in range(xGrid):
# get the dimensions of the EM layerset by looking at the dimensions of the first EM image, save for next script
imEM0 = IJ.openImage(imPaths['EM'][0])
widthEM = imEM0.width
heightEM = imEM0.height
imEM0.close()
f = open(os.path.join(registrationFolder, 'lowResEMBounds'), 'w')
pickle.dump([widthEM, heightEM], f)
f.close()

registrationStatsPath = os.path.join(registrationFolder, 'registrationStats')
registrationStats = []

# create dummy trakem for applying affine and cropping LM in the first registration step
pZ, loaderZ, layersetZ, nLayersZ = fc.getProjectUtils(
    fc.initTrakem(temporaryFolder, 1))
layersetZ.setDimensions(0, 0, widthEM * 5, heightEM * 5)
layerZ = layersetZ.getLayers().get(0)

lock = threading.Lock()

# Setting up the parallel threads and starting them
atomicI = AtomicInteger(0)
fc.startThreads(computeRegistration, fractionCores=1, wait=0.5)

fc.closeProject(pZ)  # close dummy trakem

# save some stats on the registration
with open(registrationStatsPath, 'w') as f:
    pickle.dump(registrationStats, f)
    ['EM', 'Project'
     ])[0]  # should I make 2 projects ? One for rigid, one for warped ?

exportedEMFolder = fc.findFoldersFromTags(
    MagCFolder, ['export_alignedEMForRegistration'])[0]
nLayers = len(os.listdir(exportedEMFolder))

registrationFolder = os.path.join(os.path.dirname(projectPath),
                                  'LMEMRegistration')

f = open(os.path.join(registrationFolder, 'lowResEMBounds'), 'r')
widthEM, heightEM = pickle.load(f)
f.close()

pZ, loaderZ, layersetZ, nLayersZ = fc.getProjectUtils(
    fc.initTrakem(registrationFolder, 1))
layersetZ.setDimensions(0, 0, widthEM * 5, heightEM * 5)
layerZ = layersetZ.getLayers().get(0)

# create the folders
for channel in channels:
    affineCroppedFolder = fc.mkdir_p(
        os.path.join(LMFolder, 'affineCropped_' + channel))

for l in range(nLayers):
    layerFolder = os.path.join(registrationFolder, 'layer_' + str(l).zfill(4))
    registeredFolder = os.path.join(layerFolder, 'registered')
    affTransformPath = os.path.join(registeredFolder, 'affineSerialized')
    if os.path.isfile(affTransformPath):
        affTransform = loaderZ.deserialize(affTransformPath)
Beispiel #6
0
# reading transforms from the low-resolution montage
IJ.log('reading the affine transform parameters from the affine montage')
transformsPath = os.path.join(MagC_EM_Folder, 'assembly_lowEM_Transforms.txt')
with (open(transformsPath, 'r')) as f:
    transforms = f.readlines()
nLayers = max([int(transforms[i]) for i in range(1, len(transforms),8) ]) + 1 # why not, could simply read the EM_Metadata parameters ...

# getting downsamplingFactor
downsamplingFactor = MagCParameters['downsample_EM']['downsamplingFactor']
factorString = str(int(1000000*downsamplingFactor)).zfill(8)

# create the normal resolution project
IJ.log('Creating project with the full size EM images')
projectPath = fc.cleanLinuxPath(os.path.join(MagC_EM_Folder,'EMProject.xml'))
projectFolder = fc.cleanLinuxPath(os.path.dirname(projectPath))
project, loader, layerset, _ = fc.getProjectUtils(fc.initTrakem(projectFolder, 1))
project.saveAs(projectPath, True)

if 'g0000' in os.listdir(os.path.join(MagCFolder, 'EMData')):
    sbemimage = True
else:
    sbemimage = False
    
# Assembling all images in the project with the transforms computed on the low res and adjusted with the scale factor
IJ.log('Assembling all images in the project with the transforms computed on the low res and adjusted with the scale factor')
paths = []
locations = []
layers = []
for i in range(0, len(transforms), 8):
    alignedPatchPath = os.path.normpath(transforms[i])
    alignedPatchName = os.path.basename(alignedPatchPath)
Beispiel #7
0
#        x = float(line.replace('\n', '').split(';')[2].split(',')[0].split('(')[1])
#        y = float(line.replace('\n', '').split(';')[2].split(',')[1].split(')')[0])
#
#        allPatchCoordinates.append([path, [x,y], k])

paths = [coordinates[0] for coordinates in allPatchCoordinates]
locations = [coordinates[1] for coordinates in allPatchCoordinates]
layers = [coordinates[2] for coordinates in allPatchCoordinates]

# create the low-res trakem project with the computed stitching coordinates
projectName = 'EMProject_' + factorString + '.xml'
projectPath = fc.cleanLinuxPath(os.path.join(MagC_EM_Folder, projectName))
IJ.log('Creating the Trakem project ' + projectName)

project, loader, layerset, nbLayers = fc.getProjectUtils(
    fc.initTrakem(fc.cleanLinuxPath(MagC_EM_Folder), nbLayers))
project.saveAs(projectPath, True)
time.sleep(1)  # probably useless
loader.setMipMapsRegeneration(False)

importFilePath = fc.createImportFile(MagC_EM_Folder,
                                     paths,
                                     locations,
                                     layers=layers,
                                     name=namePlugin + factorString)

IJ.log('I am going to insert many files at factor ' + str(downsamplingFactor))
task = loader.importImages(layerset.getLayers().get(0), importFilePath, '\t',
                           1, 1, False, 1, 0)
task.join()
Beispiel #8
0
		lines[idLine] = 'nChannels = ' + str(nChannels + 1)
	if 'channels' in line:
		lines[idLine] = 'channels = [' + ','.join( map(lambda x: "'" + x + "'", channels) ) + ']'
f.close()
f = open(LMMetadataPath, 'w')
for line in lines:
	f.write(line + '\n')
f.close()
IJ.log('addContrastedChannel done')

# Create LM project with the contrastedChannel
nLayers = len(next(os.walk(LMDataFolder))[1])
IJ.log('nLayers is ' + str(nLayers))
IJ.log('Creating trakem project "LMProject" ')

project, loader, layerset, nLayers = fc.getProjectUtils(fc.initTrakem(LMFolder, nLayers))
projectPath = os.path.join(os.path.normpath(LMFolder) , 'LMProject.xml')
project.saveAs(projectPath, True)

# determining tiles locations taking into account the overlap
paths, locations, layers = [], [], []
widthEffective = int((1-overlap) * width)
heightEffective = int((1-overlap) * height)

for channel in [contrastedChannel]:
	IJ.log('Assembling LM sections from all layers')
	for l in range(nLayers):
		IJ.log('Each section consists of ' + str(xGrid) + ' x ' + str(yGrid) + ' patches')
		for y in range(yGrid):
			for x in range(xGrid):
				sectionFolder = os.path.join(LMDataFolder, 'section_' + str(l).zfill(4))