-
Notifications
You must be signed in to change notification settings - Fork 2
/
sectionSegmentation.py
1927 lines (1532 loc) · 86.2 KB
/
sectionSegmentation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# doing simple morpghological operations might be easier than WEKA ...
# What do I want exactly ?
# approximate locations are ok
# CCs are ok, simply need to fine tune a bit more
# make a double CC on the two channels, and use a weight a.BF + (1-a).Fluo
# --preprocess correctly at the beginning
# --blend the BF channel
# --get the edge channel yes, that is a useful channel
# look for salient point in corner neighborhood ?
# (Corners are too difficult, depends on block shape ?)
# Fiji script that aligns the patches of the silicon wafer overview. It outputs subpatches x_y_imageName (normal, thesholded, edges). The overlap of the subpatches depends on the size of the template.
# # ToDos 05/2017
# --user prompt to offset the channels
# then insert the dapi channel too
# --activate automated montage
# manual section at the end should give the real section, not the mag ? tant qu'a faire, the user gives the exact section ...
# but it is annoying, because the affine mechanism is in the preImaging script, so that either I should transfer the affine mechanism into this first script or I should keep track of which sections are mag sections and which sections are real sections
# /!\ -- actually I need the affine mechanism in this script because I need to assess the orientation of the sections
# manually ?
# the affine mechanism is almost there. I can already transform sections. I need to find an affine given source and target points. It most probably already exists.
# asymmetric trimming ?
# difficult because otherwise the section terminates with mag resin
# - understand why so many sections missing that should be easy to get
# -- 0.95 was clearly too high for the area threshold
# clustering issue also ?
# weka on the brightfield to find the orientation or manual entry with a key press ?
# without systematic detachment it might not be easy to weka the orientation ...
# compare the quantity of edges on the two sides ... should be rather robust
# final GUI: export the sections to landmarks, adjust the landmarks and add new ones
from __future__ import with_statement
import os, time, pickle, shutil
# import subprocess # currently broken, use os.system instead
from java.lang import ProcessBuilder
import threading
import ij
from ij import IJ, ImagePlus, WindowManager
from ij.gui import Roi, PolygonRoi, PointRoi, WaitForUserDialog
from ij.process import ImageStatistics, ImageProcessor
from ij.measure import Measurements
from ij.plugin import ImageCalculator
from ij.plugin.frame import RoiManager
from ij.plugin.tool import RoiRotationTool
from java.awt import Frame
from java.lang import Double
import fijiCommon as fc
from ini.trakem2 import Project, ControlWindow
from ini.trakem2.display import Patch, Display, AreaList, Displayable
from ini.trakem2.imaging import StitchingTEM
from ini.trakem2.imaging import Blending
from ini.trakem2.imaging.StitchingTEM import PhaseCorrelationParam
from ij.plugin.filter import ParticleAnalyzer
from mpicbg.imglib.algorithm.correlation import CrossCorrelation
from mpicbg.trakem2.align import Align, AlignTask
from mpicbg.imglib.image import ImagePlusAdapter
from java.awt import Rectangle, Color, Polygon
from java.awt.geom import Area, AffineTransform
from java.awt.event import MouseAdapter, KeyAdapter, KeyEvent
from java.lang import Math, Runtime
from java.lang.Math import hypot, sqrt, atan2, PI, abs
from java.util.concurrent.atomic import AtomicInteger
from jarray import zeros, array
from trainableSegmentation import WekaSegmentation
from xml.dom import minidom
from operator import itemgetter
#########################################################################
# BEGIN README
#########################################################################
# 1. Start Fiji
# 2. Run this script in the Script Editor of Fiji (setting language to python)
#########################################################################
# END README
#########################################################################
def xlim(a, lbb):
return max(min(a, lbb.width), 0)
def ylim(a, lbb):
return max(min(a, lbb.height), 0)
colors = [Color.red, Color.blue, Color.green, Color.yellow, Color.cyan, Color.magenta, Color.orange]
def convertTo8BitAndResize(imagePaths, newImagePaths, downFactor, atomicI):
while atomicI.get() < len(imagePaths):
k = atomicI.getAndIncrement()
if (k < len(imagePaths)):
imagePath = imagePaths[k]
newImagePath = newImagePaths[k]
im = IJ.openImage(imagePath)
IJ.run(im, '8-bit', '')
# if 'BF' in os.path.basename(newImagePath): # normalize only the BF channel
# fc.normLocalContrast(im, 500, 500, 3, True, True)
im = fc.resize(im, float(1/float(downFactor)))
IJ.save(im, newImagePath)
IJ.log(str(k) + ' of ' + str(len(imagePaths)) + ' processed')
im.close()
#########################
### TrakEM2 operations
#########################
def addLandmarkOverlays(project, landmarks):
layerset = project.getRootLayerSet()
layer = layerset.getLayers().get(0)
layerId = layer.getId()
arealists = []
for l, landmark in enumerate(landmarks):
ali = AreaList(project, 'landmark' + '_' + str(l), 0, 0)
layerset.add(ali)
lbb = layerset.get2DBounds()
s = 500
sw = 30
poly = Polygon(map(lambda x: xlim(x, lbb), [landmark[0]-s, landmark[0]+s, landmark[0]+s, landmark[0]-s]), map(lambda x: ylim(x, lbb), [landmark[1]-sw, landmark[1]-sw, landmark[1]+sw, landmark[1]+sw]), 4)
ali.addArea(layerId, Area(poly))
poly = Polygon(map(lambda x: xlim(x, lbb), [landmark[0]-sw, landmark[0]+sw, landmark[0]+sw, landmark[0]-sw]), map(lambda x: ylim(x, lbb), [landmark[1]-s, landmark[1]-s, landmark[1]+s, landmark[1]+s]), 4)
ali.addArea(layerId, Area(poly))
ali.alpha = 0.5
ali.color = colors[l%len(colors)]
ali.visible = True
ali.locked = False
ali.calculateBoundingBox(layer)
arealists.append(ali)
ali.updateBucket()
project.getProjectTree().insertSegmentations([ali])
displays = Display.getDisplays()
if displays.isEmpty():
disp = Display(project, layer)
else:
disp = displays[0]
disp.repaint()
project.getLayerTree().updateList(layerset)
layer.recreateBuckets()
factor = 1
canvas = disp.getCanvas()
disp.repaint()
# disp.show(layer, ali, False, False)
Display.showCentered(layer, ali, False, False)
disp.repaint()
w = 500
h = 500
bb = Rectangle(int(round(landmark[0]-w/2)), int(round(landmark[1]-h/2)), w, h)
bb = bb.createIntersection(layerset.get2DBounds())
im = project.getLoader().getFlatImage(layer, bb, factor, 0x7fffffff, ImagePlus.COLOR_RGB, Displayable, True)
IJ.save(im, os.path.join(preImagingFolder, 'landmark_' + str(l) + '_zoom_1.png'))
w = 5000
h = 5000
ali.alpha = 0.8
bb = Rectangle(int(round(landmark[0]-w/2)), int(round(landmark[1]-h/2)), w, h)
bb = bb.createIntersection(layerset.get2DBounds())
disp.repaint()
im = project.getLoader().getFlatImage(layer, bb, 0.5 * factor, 0x7fffffff, ImagePlus.COLOR_RGB, Displayable, True)
IJ.save(im, os.path.join(preImagingFolder, 'landmark_' + str(l) + '_zoom_2.png'))
# # # w = 15000
# # # h = 15000
# # # ali.alpha = 1
# # # bb = Rectangle(int(landmark[0]-w/2), int(landmark[1]-h/2), w, h)
# # # bb = bb.createIntersection(layerset.get2DBounds())
# # # disp.repaint()
# # # im = project.getLoader().getFlatImage(layer, bb, 0.03 * factor, 0x7fffffff, ImagePlus.COLOR_RGB, Displayable, True)
# # # IJ.save(im, os.path.join(preImagingFolder, 'landmark_' + str(l) + '_zoom_3.png'))
# # # ali.visible = False
for ali in arealists:
ali.visible = True
im = project.getLoader().getFlatImage(layer, layerset.get2DBounds(), 0.5 * factor, 0x7fffffff, ImagePlus.COLOR_RGB, Displayable, True)
IJ.save(im, os.path.join(preImagingFolder, 'allLandmarks.png'))
# project.save()
def forceAlphas(layerset):
for ali in layerset.getZDisplayables(AreaList):
if int(ali.getFirstLayer().getZ()) == 0:
ali.alpha = 0.5
elif int(ali.getFirstLayer().getZ()) == 1:
ali.alpha = 1
# def addSectionOverlays(project, layers, sections, colors, alphas, name):
# layerset = project.getRootLayerSet()
# for l in layers:
# layer = layerset.getLayers().get(l)
# layerId = layer.getId()
# segmentations = []
# ali = AreaList(project, name + '_' + str(l), 0, 0)
# layerset.add(ali)
# for id, section in enumerate(sections):
# ali.addArea(layerId, Area(sectionToPoly(section)))
# ali.alpha = alphas[l]
# ali.color = colors[l]
# ali.visible = True
# ali.locked = False
# # ali.setColor(colors[l])
# # ali.setAlpha(alphas[l])
# ali.calculateBoundingBox(None)
# print 'alpha', ali.getAlpha(), 'layer', l
# ali.updateBucket()
# segmentations.append(ali)
# project.getProjectTree().insertSegmentations([ali])
# displays = Display.getDisplays()
# if displays.isEmpty():
# disp = Display(project, layer)
# else:
# disp = displays[0]
# disp.repaint()
# # project.getProjectTree().insertSegmentations(segmentations)
# project.getLayerTree().updateList(layerset)
# layer.recreateBuckets()
def addSectionOverlays(project, layers, sections, colors, alphas, name):
layerset = project.getRootLayerSet()
for l in layers:
layer = layerset.getLayers().get(l)
layerId = layer.getId()
segmentations = []
for id, section in enumerate(sections):
ali = AreaList(project, name + '_' + str(id), 0, 0)
layerset.add(ali)
ali.addArea(layerId, Area(sectionToPoly(section)))
ali.alpha = alphas[l]
ali.color = colors[l]
ali.visible = True
ali.locked = False
# ali.setColor(colors[l])
# ali.setAlpha(alphas[l])
ali.calculateBoundingBox(None)
print 'alpha', ali.getAlpha(), 'layer', l
ali.updateBucket()
segmentations.append(ali)
project.getProjectTree().insertSegmentations(segmentations)
displays = Display.getDisplays()
if displays.isEmpty():
disp = Display(project, layer)
else:
disp = displays[0]
disp.repaint()
# project.getProjectTree().insertSegmentations(segmentations)
project.getLayerTree().updateList(layerset)
layer.recreateBuckets()
def createImportFile(folder, paths, locations, factor = 1, layer = 0):
importFilePath = os.path.join(folder, 'trakemImportFile.txt')
with open(importFilePath, 'w') as f:
for id, path in enumerate(paths):
xLocation = int(round(locations[id][0] * factor))
yLocation = int(round(locations[id][1] * factor))
IJ.log('Inserting image ' + path + ' at (' + str(xLocation) + ' ; ' + str(yLocation) + ')' )
f.write(str(path) + '\t' + str(xLocation) + '\t' + str(yLocation) + '\t' + str(layer) + '\n')
return importFilePath
def getPointsFromUser(project, l, fov = None, text = 'Select points'):
points = None
layerset = project.getRootLayerSet()
layer = layerset.getLayers().get(l)
displays = Display.getDisplays()
if displays.isEmpty():
disp = Display(project, layer)
else:
disp = displays[0]
disp.repaint()
disp.showFront(layer)
# print 'disp.getCanvas().getMagnification()', disp.getCanvas().getMagnification()
# disp.getCanvas().center(Rectangle(int(round(fov[0])), int(round(fov[1])), int(round(effectivePatchSize)), int(round(effectivePatchSize))), 0.75)
WaitForUserDialog(text).show()
roi = disp.getRoi()
if roi:
poly = disp.getRoi().getPolygon()
points = [list(a) for a in zip(poly.xpoints, poly.ypoints)]
disp.getCanvas().getFakeImagePlus().deleteRoi()
disp.update(layerset)
return points
def getTemplates(project):
layer = project.getRootLayerSet().getLayers().get(0) # the brightfield layer
disp = Display(project, layer)
disp.showFront(layer)
WaitForUserDialog('Select in order : A. 4 corners of a section. B. 4 corners of the mag region of the same section. Then click OK.').show()
poly = disp.getRoi().getPolygon()
X = poly.xpoints
Y = poly.ypoints
nSections = len(X)/8 # the script is general enough to let the user give more sections, but only one used here ...
print 'X', X
print 'Y', Y
print 'nSections', nSections
# # # From the old pipeline, probably not useful any more
# # 1. Determining the size of the subpatches
# sectionExtent = longestDiagonal([ [X[0], Y[0]] , [X[1], Y[1]], [X[2], Y[2]], [X[3], Y[3]] ])
# patchSize = int(round(3 * sectionExtent))
# overlap = int(round(1 * sectionExtent))
# effectivePatchSize = patchSize - overlap
# print 'effectivePatchSize', effectivePatchSize
# writePoints(patchSizeAndOverlapFullResPath, [[patchSize, overlap]])
# writePoints(patchSizeAndOverlapLowResPath, [[patchSize/float(downsizingFactor), overlap/float(downsizingFactor)]])
templateSections = []
templateMags = []
userTemplateInput = [] # the points the user gave: will be used to create template with real images
for s in range(nSections): # the script is general enough to let the user give more sections, but only one used here ...
# the user has to use the naming convention
templateSection = [ [X[8*s +0], Y[8*s +0]] , [X[8*s +1], Y[8*s +1]], [X[8*s +2], Y[8*s +2]], [X[8*s +3], Y[8*s +3]] ]
userTemplateInput.append(templateSection)
templateMag = [ [X[8*s +4], Y[8*s +4]] , [X[8*s +5], Y[8*s +5]], [X[8*s +6], Y[8*s +6]], [X[8*s +7], Y[8*s +7]] ]
userTemplateInput.append(templateMag)
print 'templateSection', templateSection
print 'templateMag', templateMag
# calculate angle of the template section (based on the magnetic part)
angle = getAngle([templateMag[0][0], templateMag[0][1], templateMag[1][0], templateMag[1][1]]) #the angle is calculated on the mag box
rotTransform = AffineTransform.getRotateInstance(-angle)
# rotate the template so that tissue is on the left, magnetic on the right (could be rotate 90deg actually ... but backward compatibility ...)
templateSection = applyTransform(templateSection, rotTransform)
templateMag = applyTransform(templateMag, rotTransform)
# after rotation, the template points are likely negative, or at least far from (0,0): translate the topleft corner of the tissue bounding box (when magnetic pointing to right) to (100,100)
bb = sectionToPoly(templateSection).getBounds() # the offset is calculated on the section box
translateTransform = AffineTransform.getTranslateInstance(- bb.x + 100, - bb.y + 100)
templateSection = applyTransform(templateSection, translateTransform)
templateMag = applyTransform(templateMag, translateTransform)
print 'templateSection', templateSection
print 'templateMag', templateMag
templateSections.append(templateSection)
templateMags.append(templateMag)
writeSections(templateSectionsPath, templateSections)
writeSections(templateMagsPath, templateMags)
writeSections(userTemplateInputPath, userTemplateInput) # to create a template image for template matching
writeSections(sourceTissueMagDescriptionPath, [templateSections[0], templateMags[0]])
def getLandmarks(project, savePath, text):
landmarks = []
layer = project.getRootLayerSet().getLayers().get(0)
disp = Display(project, layer)
disp.showFront(layer)
WaitForUserDialog(text).show()
roi = disp.getRoi()
IJ.log('ROI landmarks' + str(roi))
if roi:
poly = roi.getPolygon()
landmarks = [list(a) for a in zip(poly.xpoints, poly.ypoints)]
IJ.log('landmarks' + str(landmarks))
writePoints(savePath, landmarks)
return landmarks
def getROIDescription(project):
layer = project.getRootLayerSet().getLayers().get(0)
disp = Display(project, layer)
disp.showFront(layer)
WaitForUserDialog('Click on the 4 corners of a section. Then click on the 4 corners defining the ROI to be imaged. You can postpone that task to later').show()
roi = disp.getRoi()
if roi:
poly = roi.getPolygon()
section = [list(a) for a in zip(poly.xpoints[:4], poly.ypoints[:4])]
ROI = [list(a) for a in zip(poly.xpoints[4:], poly.ypoints[4:])]
writeSections(sourceROIDescriptionPath, [section, ROI])
#########################
### Section operations
#########################
def sectionToPoly(l):
return Polygon( [int(round(a[0])) for a in l] , [int(round(a[1])) for a in l], len(l))
def writePoints(path, points):
with open(path, 'w') as f:
for point in points:
line = str(int(round(point[0]))) + '\t' + str(int(round(point[1]))) + '\n'
IJ.log(line)
f.write(line)
IJ.log('The point coordinates have been written')
def readPoints(path):
points = []
with open(path, 'r') as f:
lines = f.readlines()
for point in lines:
points.append(map(int,point.split('\t')))
return points
def readSectionCoordinates(path, downFactor = 1):
sections = []
if os.path.isfile(path):
f = open(path, 'r')
lines = f.readlines()
for line in lines:
points = line.split('\t')
points.pop()
# print points
section = [ [int(round(float(point.split(',')[0])/float(downFactor))), int(round(float(point.split(',')[1])/float(downFactor)))] for point in points]
sections.append(section)
f.close()
return sections
def readMISTLocations(MISTPath):
patchPaths = []
patchLocations = []
f = open(MISTPath, 'r')
lines = f.readlines()
for line in lines:
patchPath = os.path.join(inputFolder8bit, line.split(';')[0].split(':')[1][1:])
x = int(round(float(line.split(';')[2].split(':')[1].split('(')[1].split(',')[0])))
y = int(round(float(line.split(';')[2].split(':')[1].split(',')[1][1:].split(')')[0])))
patchPaths.append(patchPath)
patchLocations.append([x,y])
f.close()
return patchPaths, patchLocations
def readStitchedLocations(path):
f = open(path, 'r')
lines = f.readlines()[4:] # trimm the heading
f.close()
patchPaths = []
patchLocations = []
for line in lines:
patchPath = os.path.join(inputFolder8bit, line.replace('\n', '').split(';')[0])
x = int(float(line.replace('\n', '').split(';')[2].split(',')[0].split('(')[1]))
y = int(float(line.replace('\n', '').split(';')[2].split(',')[1].split(')')[0]))
patchPaths.append(patchPath)
patchLocations.append([x,y])
return patchPaths, patchLocations
def sectionToList(pointList): # [[1,2],[5,8]] to [1,2,5,8]
l = array(2 * len(pointList) * [0], 'd')
for id, point in enumerate(pointList):
l[2*id] = point[0]
l[2*id+1] = point[1]
return l
def listToSection(l): # [1,2,5,8] to [[1,2],[5,8]]
pointList = []
for i in range(len(l)/2):
pointList.append([l[2*i], l[2*i+1]])
return pointList
def offsetCorners(corners, xOffset, yOffset):
for id, corner in enumerate(corners):
corners[id] = [corner[0] + xOffset, corner[1] + yOffset ]
return corners
def writeSections(path, sectionList):
with open(path, 'w') as f:
for section in sectionList:
for corner in section:
# print 'corner', corner
f.write( str(int(round(corner[0]))) + ',' + str(int(round(corner[1]))) + '\t')
f.write('\n')
print 'The coordinates of', len(sectionList), 'sections have been written to', path
#########################
### Geometric operations
#########################
def barycenter(points):
xSum = 0
ySum = 0
for i,point in enumerate(points):
xSum = xSum + point[0]
ySum = ySum + point[1]
x = int(round(xSum/float(i+1)))
y = int(round(ySum/float(i+1)))
return x,y
def shrink(section, factor = 0):
'''
factor = 0 : nothing happens
factor = 1 : complete shrinkage to center
'''
f = factor
# center = [(section[0][0] + section[1][0] + section[2][0] + section[3][0])/4., (section[0][1] + section[1][1] + section[2][1] + section[3][1])/4.]
center = barycenter(section)
p0, p1, p2, p3 = section # the 4 points of the section
p0 = [int(round((1-f) * p0[0] + f * center[0])) , int(round((1-f) * p0[1] + f * center[1]))]
p1 = [int(round((1-f) * p1[0] + f * center[0])) , int(round((1-f) * p1[1] + f * center[1]))]
p2 = [int(round((1-f) * p2[0] + f * center[0])) , int(round((1-f) * p2[1] + f * center[1]))]
p3 = [int(round((1-f) * p3[0] + f * center[0])) , int(round((1-f) * p3[1] + f * center[1]))]
return [p0, p1, p2, p3]
def getAngle(line):
diff = [line[0] - line[2], line[1] - line[3]]
theta = Math.atan2(diff[1], diff[0])
return theta
def longestDiagonal(corners):
maxDiag = 0
for corner1 in corners:
for corner2 in corners:
maxDiag = Math.max(Math.sqrt((corner2[0]-corner1[0]) * (corner2[0]-corner1[0]) + (corner2[1]-corner1[1]) * (corner2[1]-corner1[1])), maxDiag)
return int(maxDiag)
def getArea(section):
bb = sectionToPoly(section).getBounds()
section = [[point[0] - bb.x, point[1]-bb.y] for point in section]
im = IJ.createImage('', '8-bit', bb.width, bb.height, 1)
ip = im.getProcessor()
ip.setRoi(sectionToPoly(section))
area = ImageStatistics.getStatistics(ip, Measurements.MEAN, im.getCalibration()).area
im.close()
return area
def getConnectedComponents(im, minSize = 0):
IJ.run(im, 'Invert', '')
points = []
roim = RoiManager(True)
pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER + ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES, Measurements.AREA, None, 0, Double.POSITIVE_INFINITY, 0.0, 1.0)
pa.setRoiManager(roim)
pa.analyze(im)
for roi in roim.getRoisAsArray():
# IJ.log(str(len(roi.getContainedPoints())) + '-' + str(minSize))
if len(roi.getContainedPoints()) > minSize:
points.append(roi.getContourCentroid()) # center of mass instead ? There is nothing better apparently ...
roim.close()
return points
def getFastCC(im1,im2):
cc = CrossCorrelation(im1, im2)
cc.process()
return cc.getR()
def rotate(im, angleDegree):
ip = im.getProcessor()
ip.setInterpolationMethod(ImageProcessor.BILINEAR)
ip.rotate(angleDegree)
def getCroppedRotatedWindow(im, rDegree, x, y): # warning: uses quite a few global parameters
candidate = im.duplicate() # necessary, I cannot get it to work otherwise (the roi does not reset or something like this ...)
wCandidate = candidate.getWidth()
hCandidate = candidate.getHeight()
rotate(candidate, rDegree)
candidate.setRoi(wCandidate/2 - wTemplate, hCandidate/2 - hTemplate, wTemplate * 2, hTemplate * 2)
croppedRotatedCandidate = candidate.crop()
# the top left corner of the sliding window: middle - template/2 - neighborhood/2 + advancement
# xWindow = int(wTemplate - wTemplate/2. - neighborhood/2. + xStep * x)
# yWindow = int(hTemplate - hTemplate/2. - neighborhood/2. + yStep * y)
xWindow = x
yWindow = y
# dapi location of the sliding template patch: topleft corner + templateDapi
newTemplateDapiCenter = [templateDapiCenter[0] + xWindow, templateDapiCenter[1] + yWindow]
# distance between the dapiCenter of the sliding template and of the candidate (in the middle of the candidate)
dapiDistances = sqrt((newTemplateDapiCenter[0] - wTemplate)*(newTemplateDapiCenter[0] - wTemplate) + (newTemplateDapiCenter[1] - hTemplate)*(newTemplateDapiCenter[1] - hTemplate))
# crop the candidate below the sliding template
croppedRotatedCandidate.setRoi(xWindow, yWindow, wTemplate, hTemplate)
return croppedRotatedCandidate.crop()
def templateMatchCandidate(atom, candidatePaths, templateMatchingPath, allResults):
template = ImagePlusAdapter.wrap(IJ.openImage(templateMatchingPath))
while atom.get() < len(candidatePaths):
k = atom.getAndIncrement()
if k < len(candidatePaths):
IJ.log('Processing section ' + str(k))
candidatePath = candidatePaths[k]
cand = IJ.openImage(candidatePath)
wCandidate = cand.getWidth()
hCandidate = cand.getHeight()
results = []
for rotationId in range(rotations):
candidate = cand.duplicate() # necessary, I cannot get it to work otherwise (the roi does not reset or something like this ...)
# rotate the candidate
rotationDegree = rotationStepDegree * rotationId
rotate(candidate, rotationDegree)
# ip = candidate.getProcessor()
# ip.setInterpolationMethod(ImageProcessor.BILINEAR)
# ip.rotate(rotationDegree)
# extract a central region of the rotation candidate, size is template*2 - is that really necessary ?
# candidate.setRoi(wCandidate/2 - wTemplate, hCandidate/2 - hTemplate, wTemplate * 2, hTemplate * 2)
# croppedRotatedCandidate = candidate.crop()
# loops for the brute force search
for x in range(xMatchingGrid):
for y in range(yMatchingGrid):
# the top left corner of the sliding window: middle - template/2 - neighborhood/2 + advancement
xWindow = int(wCandidate/2. - wTemplate/2. - neighborhood/2. + xStep * x)
yWindow = int(hCandidate/2. - hTemplate/2. - neighborhood/2. + yStep * y)
# dapi location of the sliding template patch: topleft corner + templateDapi
newTemplateDapiCenter = [templateDapiCenter[0] + xWindow, templateDapiCenter[1] + yWindow]
# distance between the dapiCenter of the sliding template and of the candidate (in the middle of the candidate)
dapiDistances = sqrt((newTemplateDapiCenter[0] - wTemplate)*(newTemplateDapiCenter[0] - wTemplate) + (newTemplateDapiCenter[1] - hTemplate)*(newTemplateDapiCenter[1] - hTemplate))
# IJ.log(str(dapiDistances))
if dapiDistances < dapiCenterDistanceThreshold:
# if dapiDistances < 99999:
# crop the candidate below the sliding template patch
candidate.setRoi(xWindow, yWindow, wTemplate, hTemplate)
croppedRotatedCandidate = candidate.crop()
# IJ.log('-----' + str(croppedRotatedCandidate.getWidth()))
croppedRotatedCandidate = ImagePlusAdapter.wrap(croppedRotatedCandidate)
# compute CC and append result
cc = getFastCC(template, croppedRotatedCandidate)
results.append([cc , [rotationDegree, x, y]])
# close open images
cand.close()
croppedRotatedCandidate.close()
candidate.close()
# sort results and append to total results
sortedResults = sorted(results, key=itemgetter(0), reverse=True) # maybe sort with the Id instead ?
# sortedResults = sorted(results, key=itemgetter(1), reverse=True) # maybe sort with the Id instead ?
# IJ.log(str(sortedResults[:5]))
bestId = sortedResults[0][1]
allResults.append([k] + sortedResults)
# # optional display of the best candidates
# im = IJ.openImage(candidatePath)
# rotationDegree = bestId[0]
# rotate(im, rotationDegree)
# im.setRoi(int(wCandidate/2. - wTemplate/2. - neighborhood/2. + xStep * bestId[1]) , int(hCandidate/2. - hTemplate/2. - neighborhood/2. + yStep * bestId[2]), wTemplate, hTemplate)
# im = im.crop()
# im.show()
# 8/0
#########################
### Affine transform operations
#########################
def applyTransform(section, aff):
sourceList = sectionToList(section)
targetList = array(len(sourceList) * [0], 'd')
aff.transform(sourceList, 0, targetList, 0, len(section))
targetSection = listToSection(targetList)
return targetSection
def affineT(sourceLandmarks, targetLandmarks, sourcePoints):
aff = fc.getModelFromPoints(sourceLandmarks, targetLandmarks).createAffine()
return applyTransform(sourcePoints, aff)
#######################
# Parameters to provide
#######################
inputFolder = os.path.normpath(r'D:\ThomasT\Thesis\B6\B6_Wafer1_203_24_12\AllImages')
###################
# Get the mosaic configuration
###################
# mosaicMetadataPath = os.path.join(os.path.dirname(inputFolder), 'Mosaic_Metadata.xml')
try:
# mosaicMetadataPath = os.path.join(os.path.dirname(inputFolder), filter(lambda x: 'metadata' in x, os.listdir(os.path.dirname(inputFolder)))[0]) # ugly ...
mosaicMetadataPath = os.path.join(inputFolder, filter(lambda x: 'Mosaic_Metadata' in x, os.listdir(inputFolder))[0]) # ugly ...
IJ.log('Using grid size from the ZEN metadate file')
xmldoc = minidom.parse(mosaicMetadataPath)
xGrid = int(float(xmldoc.getElementsByTagName('Columns')[0].childNodes[0].nodeValue))
yGrid = int(float(xmldoc.getElementsByTagName('Rows')[0].childNodes[0].nodeValue))
except Exception, e:
IJ.log('No metadata file found')
IJ.log('Using manually entered grid size for the mosaic')
xGrid = 1
yGrid = 1
IJ.log('Mosaic size: (' + str(xGrid) + ', ' + str(yGrid) + ')')
channels = ['BF', 'DAPI', '488', '546']
nChannels = len(channels)
overlap = 0.1
downsizingFactor = 3
shrinkFactor = 2 # for orientation flipping
calibrationX = 1.302428227746592
calibrationY = 1.302910064239829
#########################
# Parameters for template matching
#########################
xMatchingGrid = 10 # number of locations tested with the template on the x axis
yMatchingGrid = 10
neighborhood = 25 # neighborhood around the center tested for matching
xStep = neighborhood/xMatchingGrid
yStep = neighborhood/yMatchingGrid
rotations = 180 # number of rotations tested within the total 360 degrees
rotationStepDegree = 360/float(rotations)
rotationStepRadian = rotationStepDegree * PI / 180.
dapiCenterDistanceThreshold = 9999 # during brute force matching, the DAPI of the template and the DAPI of the candidate should be close
tissueShrinkingForEdgeFreeRegion = 0.6
#######################
# Setting up
IJ.log('Setting up')
#######################
#######################
# Getting the template
#######################
ControlWindow.setGUIEnabled(False)
workingFolder = fc.mkdir_p(os.path.join(os.path.dirname(inputFolder), 'workingFolder'))
templatePath = os.path.join(workingFolder,'templateCoordinates.txt')
inputFolderContent = os.listdir(inputFolder)
inputFolder8bit = os.path.join(workingFolder, '8bit' + os.path.basename(inputFolder))
fc.mkdir_p(inputFolder8bit)
inputFolder8bitContent = os.listdir(inputFolder8bit)
inputFolder8bitFullRes = os.path.join(workingFolder, '8bitFullRes' + os.path.basename(inputFolder))
fc.mkdir_p(inputFolder8bitFullRes)
inputFolder8bitFullResContent = os.listdir(inputFolder8bitFullRes)
fluoOffsetPath = os.path.join(workingFolder, 'fluoOffset.txt')
templateSectionsPath = os.path.join(workingFolder, 'templateSections.txt')
templateMagsPath = os.path.join(workingFolder, 'templateMags.txt')
templateSectionsLowResPath = os.path.join(workingFolder, 'templateSectionsLowRes.txt')
templateMagsLowResPath = os.path.join(workingFolder, 'templateMagsLowRes.txt')
userTemplateInputPath = os.path.join(workingFolder, 'userTemplateInputPath.txt')
preImagingFolder = fc.mkdir_p(os.path.join(workingFolder, 'preImaging'))
landmarksPath = os.path.join(preImagingFolder, 'source_landmarks.txt')
sourceTissueMagDescriptionPath = os.path.join(preImagingFolder, 'source_tissue_mag_description.txt') #2 sections: template tissue and template mag
sourceROIDescriptionPath = os.path.join(preImagingFolder, 'source_ROI_description.txt') #2 sections: template tissue and ROI
patchSizeAndOverlapFullResPath = os.path.join(workingFolder, 'patchSizeAndOverlapFullRes.txt')
patchSizeAndOverlapLowResPath = os.path.join(workingFolder, 'patchSizeAndOverlapLowRes.txt')
# print "filter(lambda x: '_Edges' in x, os.listdir(workingFolder))", filter(lambda x: '_Edges' in x, os.listdir(workingFolder))
magSectionsLowResPath = os.path.join(workingFolder, 'allMagSectionsCoordinatesLowRes.txt')
tissueSectionsLowResPath = os.path.join(workingFolder, 'allTissueSectionsCoordinatesLowRes.txt')
magSectionsHighResPath = os.path.join(workingFolder, 'allMagSectionsCoordinatesFullRes.txt')
tissueSectionsHighResPath = os.path.join(workingFolder, 'allTissueSectionsCoordinatesFullRes.txt')
finalMagSectionsPath = os.path.join(workingFolder, 'finalMagSectionsCoordinates.txt')
finalTissueSectionsPath = os.path.join(workingFolder, 'finalTissueSectionsCoordinates.txt')
finalMagSectionsPreImagingPath = os.path.join(preImagingFolder, 'source_sections_mag.txt')
finalTissueSectionsPreImagingPath = os.path.join(preImagingFolder, 'source_sections_tissue.txt')
flipFlag = os.path.join(workingFolder, 'flipflag')
### Matching files and folders ###
dapiCentersPath = os.path.join(workingFolder, 'dapiCenters')
sectionsSpecsPath = os.path.join(workingFolder, 'sectionsSpecs')
#######################
# 0.0 Converting all images to 8 bit and downsizing
#######################
if len(filter(lambda x: os.path.splitext(x)[1] == '.tif', inputFolder8bitContent)) < len(filter(lambda x: os.path.splitext(x)[1] == '.tif', inputFolderContent)):
IJ.log('0. 8-bit conversion and downsizing')
imageNames = filter(lambda x: os.path.splitext(x)[1] == '.tif', inputFolderContent)
imagePaths = [os.path.join(inputFolder, imageName) for imageName in imageNames]
newImagePaths = [os.path.join(inputFolder8bit, imageName) for imageName in imageNames]
atomicI = AtomicInteger(0)
fc.startThreads(convertTo8BitAndResize, fractionCores = 0.9, wait = 0, arguments = (imagePaths, newImagePaths, downsizingFactor, atomicI))
#######################
# 0.1 Converting all images to 8 bit, for full res
#######################
if len(filter(lambda x: os.path.splitext(x)[1] == '.tif', inputFolder8bitFullResContent)) < len(filter(lambda x: os.path.splitext(x)[1] == '.tif', inputFolderContent)):
IJ.log('0. 8-bit conversion for full res')
imageNames = filter(lambda x: os.path.splitext(x)[1] == '.tif', inputFolderContent)
imagePaths = [os.path.join(inputFolder, imageName) for imageName in imageNames]
newImagePaths = [os.path.join(inputFolder8bitFullRes, imageName) for imageName in imageNames]
atomicI = AtomicInteger(0)
fc.startThreads(convertTo8BitAndResize, fractionCores = 0.9, wait = 0, arguments = (imagePaths, newImagePaths, 1, atomicI))
#######################
# 1. Assembling the overview
#######################
# setting up trakem project
trakemFolder = workingFolder
projectPath = os.path.join(os.path.normpath(trakemFolder) , 'WaferLMProject.xml') # the project with 7 layers (low res I believe)
projectPathBis = os.path.join(os.path.normpath(trakemFolder) , 'WaferLMProjectBis.xml')
projectPathFullRes = os.path.join(os.path.normpath(trakemFolder) , 'WaferLMProjectFullRes.xml')
overlaysProjectPath = os.path.join(os.path.normpath(trakemFolder) , 'OverlaysWaferLMProject.xml')
# Image names from ZEN
# Wafer_SFN_2016_b0s0c0x1249-1388y3744-1040m45.tif
imageNames = []
if not os.path.isfile(projectPath):
IJ.log('1. Assembling the overview')
imageNames = []
for channelId, channel in enumerate(channels):
# imageNames = fc.naturalSort(filter(lambda x: (os.path.splitext(x)[1] in ['.tif', '.TIF']) and ('c' + str(channelId) + 'x') in x , os.listdir(inputFolder8bit)))
if channel == 'BF': # BF and fluo channels have different naming schemes at the Z1 microscope because all fluo chanels imaged together and the BF imaged separately (because high intensity needed for fluo but low intensity needed for BF)
imageNames = fc.naturalSort(filter(lambda x: (os.path.splitext(x)[1] in ['.tif', '.TIF']) and (('c' + str(channelId) + 'x') in x) and ('BF' in x) , os.listdir(inputFolder8bit)))
else:
imageNames = fc.naturalSort(filter(lambda x: (os.path.splitext(x)[1] in ['.tif', '.TIF']) and ('c' + str(channelId-1) + 'x') in x , os.listdir(inputFolder8bit)))
# Wafer_210_BF_b0s0c0x3747-1388y0-1040m3
# Wafer_210_DAPI_488_546_b0s0c0x4996-1388y11232-1040m112
if channelId == 0:
# # commented lines below probably to delete
# im0 = IJ.openImage(os.path.join(inputFolder8bit, imageNames[0]))
# width = im0.getWidth()
# height = im0.getHeight()
# im0.close()
# widthEffective = int(round((1-overlap) * width))
# heightEffective = int(round((1-overlap) * height))
project, loader, layerset, nLayers = fc.getProjectUtils(fc.initTrakem(trakemFolder, nChannels + 3)) #channels + thresholded + edged + rawEdged
loader.setMipMapsRegeneration(False)
project.saveAs(projectPath, True)
layer = layerset.getLayers().get(channelId)
# inserting all patches
patchPaths = []
patchLocations = []
# for x in range(xGrid):
# for y in range(yGrid):
# patchNumber = y * xGrid + x * (1 - (y%2)) + (xGrid - x - 1) * (y%2)
# patchNumber = x * yGrid + y * (1 - (x%2)) + (yGrid - y - 1) * (x%2)
# patchNumber = x * yGrid + y
# renaming to e.g. DAPI_038.tif for stitching plugin instead of the ZEN names
for imageId, imageName in enumerate(fc.naturalSort(imageNames)):
sourcePatchPath = os.path.join(inputFolder8bit, imageName)
targetPatchPath = os.path.join(inputFolder8bit, channel + '_' + str(imageId).zfill(3) + '.tif')
os.rename(sourcePatchPath, targetPatchPath)
# patchPaths.append()
# xmldoc = minidom.parse(os.path.join(inputFolder, imageName + '_metadata.xml'))
# patchLocations.append([int(float(xmldoc.getElementsByTagName('StageXPosition')[0].childNodes[0].nodeValue)/float(calibrationX)/float(downsizingFactor)) + 10000, int(float(xmldoc.getElementsByTagName('StageYPosition')[0].childNodes[0].nodeValue)/float(calibrationY)/float(downsizingFactor)) + 10000])
if (xGrid * yGrid) != 1:
patchLocationsPath = os.path.join(inputFolder8bit, 'TileConfiguration.registered.txt') # patch locations calculated by the plugin
if not os.path.isfile(patchLocationsPath):
# Grid/Collection stitching plugin has issues with section-free areas
command = 'type=[Grid: column-by-column] order=[Down & Right ] grid_size_x=' + str(xGrid) + ' grid_size_y=' + str(yGrid) + ' tile_overlap=' + str(overlap * 100) + ' first_file_index_i=0 directory=' + inputFolder8bit + ' file_names=BF_{iii}.tif output_textfile_name=TileConfiguration.txt fusion_method=[Linear Blending] regression_threshold=0.30 max/avg_displacement_threshold=2.50 absolute_displacement_threshold=3.50 compute_overlap computation_parameters=[Save computation time (but use more RAM)] image_output=[Write to disk] output_directory=' + inputFolder8bit
IJ.log('Stitching command - ' + command)
IJ.run('Grid/Collection stitching', command)
# # The MIST plugin does not seem to have problems with the section-free areas, but more inaccurate
# IJ.run('MIST', 'gridwidth=' + str(xGrid) + ' gridheight=' + str(yGrid) + ' starttile=0 imagedir=' + inputFolder8bit + ' filenamepattern=' + channel + '_{ppp}.tif filenamepatterntype=SEQUENTIAL gridorigin=UL assemblefrommetadata=false globalpositionsfile=[] numberingpattern=VERTICALCOMBING startrow=0 startcol=0 extentwidth=' + str(xGrid) + ' extentheight=' + str(yGrid) + ' timeslices=0 istimeslicesenabled=false issuppresssubgridwarningenabled=false outputpath=' + inputFolder8bit + ' displaystitching=false outputfullimage=false outputmeta=true outputimgpyramid=false blendingmode=OVERLAY blendingalpha=NaN outfileprefix=img- programtype=AUTO numcputhreads=' + str(Runtime.getRuntime().availableProcessors()) + ' loadfftwplan=true savefftwplan=true fftwplantype=MEASURE fftwlibraryname=libfftw3 fftwlibraryfilename=libfftw3.dll planpath=' + os.path.join(IJ.getDirectory('imagej'), 'lib', 'fftw', 'fftPlans') + ' fftwlibrarypath=' + os.path.join(IJ.getDirectory('imagej'), 'lib', 'fftw') + ' stagerepeatability=0 horizontaloverlap=' + str(overlap * 100) + ' verticaloverlap=' + str(overlap * 100) + ' numfftpeaks=0 overlapuncertainty=NaN isusedoubleprecision=false isusebioformats=false isenablecudaexceptions=false translationrefinementmethod=SINGLE_HILL_CLIMB numtranslationrefinementstartpoints=16 headless=false loglevel=MANDATORY debuglevel=NONE')
# patchLocationsPath = os.path.join(inputFolder8bit, 'img-global-positions-0.txt')
# patchPaths, patchLocations = readMISTLocations(patchLocationsPath)
patchPaths, patchLocations = readStitchedLocations(patchLocationsPath)
else:
patchLocations.append([0,0])
patchPaths.append(os.path.join(inputFolder8bit, channel + '_' + str(0).zfill(3) + '.tif'))
IJ.log('patchPaths ' + str(patchPaths))
IJ.log('patchLocations ' + str(patchLocations))
# import all patches in the trakEM project
importFilePath = createImportFile(workingFolder, patchPaths, patchLocations)
task = loader.importImages(layerset.getLayers().get(channelId), importFilePath, '\t', 1, 1, False, 1, 0)
task.join()
# # # # # # /!\ old version with the phase correlation TEM stitcher
# # # #######################
# # # # 2. Montaging the overview
# # # IJ.log('2. Montaging the overview')
# # # #######################
# # # patchScale, hide_disconnected, remove_disconnected, mean_factor, min_R = 1, False, False, 2.5, 0.1
# # # stitcher = StitchingTEM()
# # # params = PhaseCorrelationParam(patchScale, overlap, hide_disconnected, remove_disconnected, mean_factor, min_R)
# # # collectionPatches = layer.getDisplayables(Patch)
# # # stitcher.montageWithPhaseCorrelation(collectionPatches, params)
else: # stitching has already been done in the first channel, simply read the calculated stitching locations
# renaming to e.g. DAPI_038.tif for stitching plugin instead of the ZEN names
for imageId, imageName in enumerate(fc.naturalSort(imageNames)):
sourcePatchPath = os.path.join(inputFolder8bit, imageName)
targetPatchPath = os.path.join(inputFolder8bit, channel + '_' + str(imageId).zfill(3) + '.tif')
os.rename(sourcePatchPath, targetPatchPath)
# read the patch coordinates of stitched layer 0 of the trakem project
patches0 = layerset.getLayers().get(0).getDisplayables(Patch)
patchPaths = [os.path.join(os.path.dirname(patch.getFilePath()), os.path.basename(patch.getFilePath()).replace(channels[0], channel)) for patch in patches0]
patchLocations = [ [patch.getX() , patch.getY()] for patch in patches0]
# patchLocations = []
# for patchPath in patchPaths:
# xmldoc = minidom.parse(os.path.join(inputFolder, os.path.basename(patchPath) + '_metadata.xml'))
# patchLocations.append([int(float(xmldoc.getElementsByTagName('StageXPosition')[0].childNodes[0].nodeValue)/float(calibrationX)/float(downsizingFactor)) + 10000 , int(float(xmldoc.getElementsByTagName('StageYPosition')[0].childNodes[0].nodeValue)/float(calibrationY)/float(downsizingFactor)) + 10000])
# import patches to the trakem project
importFilePath = createImportFile(workingFolder, patchPaths, patchLocations)
task = loader.importImages(layerset.getLayers().get(channelId), importFilePath, '\t', 1, 1, False, 1, 0)
task.join()
project.save()
IJ.log('Assembling the channels done and saved into ' + projectPath)
fc.resizeDisplay(layerset)
fc.closeProject(project)
#######################
# 2. Assembling the full res overview
#######################
if not os.path.isfile(projectPathFullRes):
IJ.log('Creating the full res project: ' + str(projectPathFullRes))
project, loader, layerset, nLayers = fc.getProjectUtils(fc.initTrakem(trakemFolder, nChannels))
layerset.setDimensions(0, 0, 100000, 100000)
loader.setMipMapsRegeneration(False)
project.saveAs(projectPathFullRes, True)
layer = layerset.getLayers().get(0)
# insterting from the calculated registration does not work because there are negative values that trigger an offset of the layerset (though I do not understand why the problem does not occur in the low res project)
lowResproject, lowResloader, lowReslayerset, lowResnLayers = fc.openTrakemProject(projectPath)
for l, layer in enumerate(layerset.getLayers()):
# renaming to e.g. DAPI_038.tif for stitching plugin instead of the ZEN names
if l == 0:
imageNames = fc.naturalSort(filter(lambda x:
(os.path.splitext(x)[1] in ['.tif', '.TIF']) and
('c0x' in x) and
('BF' in x),
os.listdir(inputFolder8bitFullRes)))
else:
imageNames = fc.naturalSort(filter(lambda x:
(os.path.splitext(x)[1] in ['.tif', '.TIF']) and
('c' + str(l-1) + 'x') in x,
os.listdir(inputFolder8bitFullRes)))
for imageId, imageName in enumerate(fc.naturalSort(imageNames)):
sourcePatchPath = os.path.join(inputFolder8bitFullRes, imageName)
targetPatchPath = os.path.join(inputFolder8bitFullRes, channels[l] + '_' + str(imageId).zfill(3) + '.tif')
os.rename(sourcePatchPath, targetPatchPath)
patchPaths = []
patchLocations = []
for patch in lowReslayerset.getLayers().get(l).getDisplayables(Patch):
lowPatchPath = patch.getImageFilePath()