-
Notifications
You must be signed in to change notification settings - Fork 64
/
Stitching_Grid.java
1711 lines (1456 loc) · 54.2 KB
/
Stitching_Grid.java
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
package plugin;
import static stitching.CommonFunctions.addHyperLinkListener;
import fiji.util.gui.GenericDialogPlus;
import ij.IJ;
import ij.ImagePlus;
import ij.gui.MultiLineLabel;
import ij.gui.Roi;
import ij.gui.Toolbar;
import ij.plugin.PlugIn;
import ij.plugin.frame.RoiManager;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import loci.common.services.ServiceFactory;
import loci.formats.ChannelSeparator;
import loci.formats.FormatException;
import loci.formats.IFormatReader;
import loci.formats.ImageReader;
import loci.formats.MetadataTools;
import loci.formats.meta.IMetadata;
import loci.formats.meta.MetadataRetrieve;
import loci.formats.services.OMEXMLService;
import loci.plugins.BF;
import loci.plugins.in.ImporterOptions;
import mpicbg.models.InvertibleBoundable;
import mpicbg.models.TranslationModel2D;
import mpicbg.models.TranslationModel3D;
import mpicbg.stitching.CollectionStitchingImgLib;
import mpicbg.stitching.Downsampler;
import mpicbg.stitching.ImageCollectionElement;
import mpicbg.stitching.ImagePlusTimePoint;
import mpicbg.stitching.StitchingParameters;
import mpicbg.stitching.TextFileAccess;
import mpicbg.stitching.fusion.Fusion;
import net.imglib2.type.numeric.integer.UnsignedByteType;
import net.imglib2.type.numeric.integer.UnsignedShortType;
import net.imglib2.type.numeric.real.FloatType;
import ome.units.quantity.Length;
import stitching.CommonFunctions;
import stitching.utils.Log;
import tools.RoiPicker;
/**
*
* @author Stephan Preibisch (stephan.preibisch@gmx.de)
*
*/
public class Stitching_Grid implements PlugIn
{
final public static String version = "1.2";
final private String myURL = "http://fly.mpi-cbg.de/preibisch";
public static boolean seperateOverlapY = false;
public static int defaultGridChoice1 = 0;
public static int defaultGridChoice2 = 0;
public static int defaultGridSizeX = 2, defaultGridSizeY = 3;
public static double defaultOverlapX = 20;
public static double defaultOverlapY = 20;
public static String defaultDirectory = "";
public static String defaultSeriesFile = "";
public static boolean defaultConfirmFiles = true;
public static String defaultFileNames = "tile_{ii}.tif";
public static String defaultTileConfiguration = "TileConfiguration.txt";
public static boolean defaultAddTilesAsRois = false;
public static boolean defaultComputeOverlap = true;
public static boolean defaultInvertX = false;
public static boolean defaultInvertY = false;
public static boolean defaultIgnoreZStage = false;
public static boolean defaultSubpixelAccuracy = false;
public static boolean defaultDownSample = false;
public static boolean defaultDisplayFusion = false;
public static boolean writeOnlyTileConfStatic = false;
public static boolean defaultIgnoreCalibration = false;
public static double defaultIncreaseOverlap = 0;
public static boolean defaultVirtualInput = false;
public static int defaultStartI = 1;
public static int defaultStartX = 1;
public static int defaultStartY = 1;
public static int defaultFusionMethod = 0;
public static double defaultR = 0.3;
public static double defaultRegressionThreshold = 0.3;
public static double defaultDisplacementThresholdRelative = 2.5;
public static double defaultDisplacementThresholdAbsolute = 3.5;
public static boolean defaultOnlyPreview = false;
public static int defaultMemorySpeedChoice = 0;
//Added by John Lapage: user sets this parameter to define how many adjacent files each image will be compared to
public static double defaultSeqRange = 1;
public static boolean defaultQuickFusion = true;
public static String[] resultChoices = { "Fuse and display", "Write to disk" };
public static int defaultResult = 0;
public static String defaultOutputDirectory = "";
@Override
public void run( String arg0 )
{
Log.info( "Stitching internal version: " + Stitching_Grid.version );
final GridType grid = new GridType();
final int gridType = grid.getType();
final int gridOrder = grid.getOrder();
if ( gridType == -1 || gridOrder == -1 )
return;
final GenericDialogPlus gd = new GenericDialogPlus( "Grid stitching: " + GridType.choose1[ gridType ] + ", " + GridType.choose2[ gridType ][ gridOrder ] );
if ( gridType < 5 )
{
gd.addNumericField( "Grid_size_x", defaultGridSizeX, 0 );
gd.addNumericField( "Grid_size_y", defaultGridSizeY, 0 );
if ( seperateOverlapY )
{
gd.addSlider( "Tile_overlap_x [%]", 0, 100, defaultOverlapX );
gd.addSlider( "Tile_overlap_y [%]", 0, 100, defaultOverlapY );
}
else
{
gd.addSlider( "Tile_overlap [%]", 0, 100, defaultOverlapX );
}
// row-by-row, column-by-column or snake
// needs the same questions
if ( grid.getType() < 4 )
{
gd.addNumericField( "First_file_index_i", defaultStartI, 0 );
}
else
{
gd.addNumericField( "First_file_index_x", defaultStartX, 0 );
gd.addNumericField( "First_file_index_y", defaultStartY, 0 );
}
}
if ( gridType == 6 && gridOrder == 1 )
{
gd.addFileField( "Multi_series_file", defaultSeriesFile, 50 );
}
else
{
gd.addDirectoryField( "Directory", defaultDirectory, 50 );
// Modified by John Lapage: copying the general setup for Unknown Positions option
if ( gridType == 5 || gridType == 7)
gd.addCheckbox( "Confirm_files", defaultConfirmFiles );
if ( gridType < 5 )
gd.addStringField( "File_names for tiles", defaultFileNames, 50 );
if ( gridType == 6 )
gd.addStringField( "Layout_file", defaultTileConfiguration, 50 );
else
gd.addStringField( "Output_textfile_name", defaultTileConfiguration, 50 );
}
gd.addChoice( "Fusion_method", CommonFunctions.fusionMethodListGrid, CommonFunctions.fusionMethodListGrid[ defaultFusionMethod ] );
gd.addNumericField( "Regression_threshold", defaultRegressionThreshold, 2 );
gd.addNumericField( "Max/avg_displacement_threshold", defaultDisplacementThresholdRelative, 2 );
gd.addNumericField( "Absolute_displacement_threshold", defaultDisplacementThresholdAbsolute, 2 );
// added by John Lapage: creates text box in which the user can set which range to compare within. Would be nicer as an Integer.
if (gridType == 7)
gd.addNumericField( "Frame range to compare", defaultSeqRange, 0 );
gd.addCheckbox("Add_tiles_as_ROIs", defaultAddTilesAsRois);
if ( gridType < 5 )
gd.addCheckbox( "Compute_overlap (otherwise use approximate grid coordinates)", defaultComputeOverlap );
else if ( gridType == 6 && gridOrder == 0 )
gd.addCheckbox( "Compute_overlap (otherwise apply coordinates from layout file)", defaultComputeOverlap );
else if ( gridType == 6 && gridOrder == 1 )
{
gd.addCheckbox( "Compute_overlap (otherwise trust coordinates in the file)", defaultComputeOverlap );
gd.addCheckbox( "Ignore_Calibration", defaultIgnoreCalibration );
gd.addSlider( "Increase_overlap [%]", 0, 100, defaultIncreaseOverlap );
}
gd.addCheckbox( "Invert_X coordinates", defaultInvertX );
gd.addCheckbox( "Invert_Y coordinates", defaultInvertY );
gd.addCheckbox( "Ignore_Z_stage position", defaultIgnoreZStage);
gd.addCheckbox( "Subpixel_accuracy", defaultSubpixelAccuracy );
gd.addCheckbox( "Downsample_tiles", defaultDownSample);
gd.addCheckbox( "Display_fusion", defaultDisplayFusion);
gd.addCheckbox( "Use_virtual_input_images (Slow! Even slower when combined with subpixel accuracy during fusion!)", defaultVirtualInput );
gd.addChoice( "Computation_parameters", CommonFunctions.cpuMemSelect, CommonFunctions.cpuMemSelect[ defaultMemorySpeedChoice ] );
gd.addChoice( "Image_output", resultChoices, resultChoices[ defaultResult ] );
gd.addMessage("");
gd.addMessage( "This Plugin is developed by Stephan Preibisch\n" + myURL);
MultiLineLabel text = (MultiLineLabel) gd.getMessage();
addHyperLinkListener(text, myURL);
gd.showDialog();
if ( gd.wasCanceled() )
return;
// the general stitching parameters
final StitchingParameters params = new StitchingParameters();
final int gridSizeX, gridSizeY;
double overlapX, overlapY;
int startI = 0, startX = 0, startY = 0;
if ( gridType < 5 )
{
gridSizeX = defaultGridSizeX = (int)Math.round(gd.getNextNumber());
gridSizeY = defaultGridSizeY = (int)Math.round(gd.getNextNumber());
if ( seperateOverlapY )
{
overlapX = defaultOverlapX = gd.getNextNumber();
overlapX /= 100.0;
overlapY = defaultOverlapY = gd.getNextNumber();
overlapY /= 100.0;
}
else
{
overlapX = overlapY = defaultOverlapY = defaultOverlapX = gd.getNextNumber();
overlapX /= 100.0;
overlapY = overlapX;
}
// row-by-row, column-by-column or snake
// needs the same questions
if ( grid.getType() < 4 )
{
startI = defaultStartI = (int)Math.round(gd.getNextNumber());
}
else // position
{
startX = defaultStartI = (int)Math.round(gd.getNextNumber());
startY = defaultStartI = (int)Math.round(gd.getNextNumber());
}
}
else
{
gridSizeX = gridSizeY = 0;
overlapX = overlapY = 0;
}
String directory, outputFile, seriesFile;
final boolean confirmFiles;
final String filenames;
if ( gridType == 6 && gridOrder == 1 )
// "Positions from file" + "Defined by metadata"
{
seriesFile = defaultSeriesFile = gd.getNextString();
outputFile = defaultTileConfiguration;
// derive directory from the file (the dialog doesn't provide one)
directory = seriesFile.trim();
directory = directory.replace('\\', '/');
directory = directory.split("/[^/]*$")[0]; // remove the file part
filenames = null;
confirmFiles = false;
}
else
{
directory = defaultDirectory = gd.getNextString();
seriesFile = null;
// Modified by John Lapage: copying the general setup for Unknown Positions option
if ( gridType == 5 || gridType == 7)
confirmFiles = defaultConfirmFiles = gd.getNextBoolean();
else
confirmFiles = false;
if ( gridType < 5 )
filenames = defaultFileNames = gd.getNextString();
else
filenames = "";
outputFile = defaultTileConfiguration = gd.getNextString();
}
params.fusionMethod = defaultFusionMethod = gd.getNextChoiceIndex();
params.regThreshold = defaultRegressionThreshold = gd.getNextNumber();
params.relativeThreshold = defaultDisplacementThresholdRelative = gd.getNextNumber();
params.absoluteThreshold = defaultDisplacementThresholdAbsolute = gd.getNextNumber();
// Added by John Lapage: sends user specified range to the parameters object
if ( gridType == 7)
params.seqRange = (int)(defaultSeqRange = Math.round( gd.getNextNumber() ) );
final boolean addTilesAsRois = params.addTilesAsRois = defaultAddTilesAsRois = gd.getNextBoolean();
// Modified by John Lapage (rearranged). Copies the setup for Unknown Positions. User specifies this with all other options.
if ( gridType == 5 || gridType == 7)
params.computeOverlap = true;
else
params.computeOverlap = defaultComputeOverlap = gd.getNextBoolean();
final double increaseOverlap;
final boolean ignoreCalibration;
if ( gridType == 6 && gridOrder == 1 )
{
ignoreCalibration = defaultIgnoreCalibration = gd.getNextBoolean();
increaseOverlap = defaultIncreaseOverlap = gd.getNextNumber();
}
else
{
ignoreCalibration = false;
increaseOverlap = 0;
}
final boolean invertX = params.invertX = defaultInvertX = gd.getNextBoolean();
final boolean invertY = params.invertY = defaultInvertY = gd.getNextBoolean();
final boolean ignoreZStage = params.ignoreZStage = defaultIgnoreZStage = gd.getNextBoolean();
params.subpixelAccuracy = defaultSubpixelAccuracy = gd.getNextBoolean();
final boolean downSample = params.downSample = defaultDownSample = gd.getNextBoolean();
params.displayFusion = defaultDisplayFusion = gd.getNextBoolean();
params.virtual = defaultVirtualInput = gd.getNextBoolean();
params.cpuMemChoice = defaultMemorySpeedChoice = gd.getNextChoiceIndex();
params.outputVariant = defaultResult = gd.getNextChoiceIndex();
if ( params.virtual )
{
Log.warn( "Using virtual input images. This will save a lot of RAM, but will also be slower ... \n" );
if ( params.subpixelAccuracy && params.fusionMethod != CommonFunctions.fusionMethodListGrid.length - 1 )
{
Log.warn( "You combine subpixel-accuracy with virtual input images, fusion will take 2-times longer ... \n" );
}
}
if ( params.fusionMethod != CommonFunctions.fusionMethodListGrid.length - 1 && params.outputVariant == 1 )
{
if ( defaultOutputDirectory == null || defaultOutputDirectory.length() == 0 )
defaultOutputDirectory = defaultDirectory;
final GenericDialogPlus gd2 = new GenericDialogPlus( "Select output directory" );
gd2.addDirectoryField( "Output_directory", defaultOutputDirectory, 60 );
gd2.showDialog();
if ( gd2.wasCanceled() )
return;
params.outputDirectory = defaultOutputDirectory = gd2.getNextString();
}
else
{
params.outputDirectory = null;
}
final long startTime = System.currentTimeMillis();
// we need to set this
params.channel1 = 0;
params.channel2 = 0;
params.timeSelect = 0;
params.checkPeaks = 5;
//added by John Lapage: sets the parameters object to recognise that Sequential File pairing should be performed
if ( gridType == 7) params.sequential=true;
// for reading in writing the tileconfiguration file
if ( ! (gridType == 6 && gridOrder == 1 ) )
{
directory = directory.replace('\\', '/');
directory = directory.trim();
if (directory.length() > 0 && !directory.endsWith("/"))
directory = directory + "/";
}
// get all imagecollectionelements
final ArrayList< ImageCollectionElement > elements;
Downsampler ds = null;
if ( downSample && !( gridType == 5 || gridType == 7) ) ds = new Downsampler();
if ( gridType < 5 )
elements = getGridLayout( grid, gridSizeX, gridSizeY, overlapX, overlapY, directory, filenames, startI, startX, startY, params.virtual, ds );
//John Lapage modified this: copying setup for Unknown Positions
else if ( gridType == 5 || gridType == 7)
elements = getAllFilesInDirectory( directory, confirmFiles );
else if ( gridType == 6 && gridOrder == 1 ) // positions from file metadata
elements = getLayoutFromMultiSeriesFile( seriesFile, increaseOverlap,
ignoreCalibration, invertX, invertY, ignoreZStage, ds );
else if ( gridType == 6 ) // positions from tile configuration file
elements = getLayoutFromFile( directory, outputFile, ds );
else
elements = null;
if ( elements == null )
{
Log.error("Error during tile discovery, or invalid grid type. Aborting.");
return;
}
if ( elements.size() < 2 )
{
Log.error("Found: " + elements.size() +
" tiles, but at least 2 are required for stitching. Aborting.");
return;
}
// open all images (if not done already by grid parsing) and test them, collect information
int numChannels = -1;
int numTimePoints = -1;
boolean is2d = false;
boolean is3d = false;
for ( final ImageCollectionElement element : elements )
{
if ( gridType >=5 )
{
if ( params.virtual )
Log.info( "Opening VIRTUAL: " + element.getFile().getAbsolutePath() + " ... " );
else
Log.info( "Loading: " + element.getFile().getAbsolutePath() + " ... " );
}
long time = System.currentTimeMillis();
final ImagePlus imp = element.open( params.virtual );
time = System.currentTimeMillis() - time;
if ( imp == null )
return;
if (downSample && ( gridType == 5 || gridType == 7)) {
if (ds == null) {
ds = new Downsampler();
ds.getInput(imp.getWidth(), imp.getHeight());
}
ds.run(imp);
}
int lastNumChannels = numChannels;
int lastNumTimePoints = numTimePoints;
numChannels = imp.getNChannels();
numTimePoints = imp.getNFrames();
if ( imp.getNSlices() > 1 )
{
if ( gridType >=5 )
Log.info( "" + imp.getWidth() + "x" + imp.getHeight() + "x" + imp.getNSlices() + "px, channels=" + numChannels + ", timepoints=" + numTimePoints + " (" + time + " ms)" );
is3d = true;
}
else
{
if ( gridType >=5 )
Log.info( "" + imp.getWidth() + "x" + imp.getHeight() + "px, channels=" + numChannels + ", timepoints=" + numTimePoints + " (" + time + " ms)" );
is2d = true;
}
// test validity of images
if ( is2d && is3d )
{
Log.error( "Some images are 2d, some are 3d ... cannot proceed" );
return;
}
if ( ( lastNumChannels != numChannels ) && lastNumChannels != -1 )
{
Log.error( "Number of channels per image changes ... cannot proceed" );
return;
}
if ( ( lastNumTimePoints != numTimePoints ) && lastNumTimePoints != -1 )
{
Log.error( "Number of timepoints per image changes ... cannot proceed" );
return;
}
// John Lapage changed this: copying setup for Unknown Positions
if ( gridType == 5 || gridType == 7)
{
if ( is2d )
{
element.setDimensionality( 2 );
element.setModel( new TranslationModel2D() );
element.setOffset( new float[]{ 0, 0 } );
}
else
{
element.setDimensionality( 3 );
element.setModel( new TranslationModel3D() );
element.setOffset( new float[]{ 0, 0, 0 } );
}
}
}
// the dimensionality of each image that will be correlated (might still have more channels or timepoints)
final int dimensionality;
if ( is2d )
dimensionality = 2;
else
dimensionality = 3;
params.dimensionality = dimensionality;
// write the initial tileconfiguration
if ( gridType != 6 )
writeTileConfiguration( new File( directory, outputFile ), elements );
// call the final stitching
final ArrayList<ImagePlusTimePoint> optimized = CollectionStitchingImgLib.stitchCollection( elements, params );
if ( optimized == null )
return;
// output the result
for ( final ImagePlusTimePoint imt : optimized )
Log.info( imt.getImagePlus().getTitle() + ": " + imt.getModel() );
// write the file tileconfiguration
// NOTE: outputFile should never be null anyway!
if ( params.computeOverlap && outputFile != null )
{
if ( outputFile.endsWith( ".txt" ) )
outputFile = outputFile.substring( 0, outputFile.length() - 4 ) + ".registered.txt";
else
outputFile = outputFile + ".registered.txt";
writeRegisteredTileConfiguration( new File( directory, outputFile ), elements );
}
// fuse
if ( params.fusionMethod != CommonFunctions.fusionMethodListGrid.length - 1 )
{
long time = System.currentTimeMillis();
if ( params.outputDirectory == null )
Log.info( "Fuse & Display ..." );
else
Log.info( "Fuse & Write to disk (into directory '" + new File( params.outputDirectory, "" ).getAbsolutePath() + "') ..." );
IJ.showStatus("Fusing stitched image...");
// first prepare the models and get the targettype
final ArrayList<InvertibleBoundable> models = new ArrayList< InvertibleBoundable >();
final ArrayList<ImagePlus> images = new ArrayList<ImagePlus>();
boolean is32bit = false;
boolean is16bit = false;
boolean is8bit = false;
for ( final ImagePlusTimePoint imt : optimized )
{
final ImagePlus imp = imt.getImagePlus();
if ( imp.getType() == ImagePlus.GRAY32 )
is32bit = true;
else if ( imp.getType() == ImagePlus.GRAY16 )
is16bit = true;
else if ( imp.getType() == ImagePlus.GRAY8 )
is8bit = true;
images.add( imp );
}
for ( int f = 1; f <= numTimePoints; ++f )
for ( final ImagePlusTimePoint imt : optimized )
models.add( (InvertibleBoundable)imt.getModel() );
ImagePlus imp = null;
// test if there is no overlap between any of the tiles
// if so fusion can be much faster
boolean noOverlap = false;
if ( overlapX == 0 && overlapY == 0 && params.computeOverlap == false && params.subpixelAccuracy == false && grid.getType() < 4 )
{
final GenericDialogPlus gd3 = new GenericDialogPlus( "Use fast fusion algorithm" );
gd3.addMessage( "There seems to be no overlap between any of the tiles." );
gd3.addCheckbox( "Use fast fusion?", defaultQuickFusion );
gd3.showDialog();
if ( gd3.wasCanceled() )
return;
noOverlap = defaultQuickFusion = gd3.getNextBoolean();
if ( noOverlap )
Log.info( "There is no overlap between any of the tiles, using faster fusion algorithm." );
}
if ( is32bit )
imp = Fusion.fuse( new FloatType(), images, models, params.dimensionality, params.subpixelAccuracy, params.fusionMethod, params.outputDirectory, noOverlap, false, params.displayFusion );
else if ( is16bit )
imp = Fusion.fuse( new UnsignedShortType(), images, models, params.dimensionality, params.subpixelAccuracy, params.fusionMethod, params.outputDirectory, noOverlap, false, params.displayFusion );
else if ( is8bit )
imp = Fusion.fuse( new UnsignedByteType(), images, models, params.dimensionality, params.subpixelAccuracy, params.fusionMethod, params.outputDirectory, noOverlap, false, params.displayFusion );
else
Log.error( "Unknown image type for fusion." );
Log.info( "Finished fusion (" + (System.currentTimeMillis() - time) + " ms)");
Log.info( "Finished ... (" + (System.currentTimeMillis() - startTime) + " ms)");
if ( imp != null )
{
imp.setTitle( "Fused" );
imp.show();
}
if (addTilesAsRois) {
double[] offset = new double[dimensionality];
Fusion.estimateBounds(offset, new int[dimensionality], images, models,
dimensionality);
generateRois(offset, optimized);
RoiManager rm = RoiManager.getInstance();
if (imp == null) {
// Save the rois
rm.runCommand("save", new File(params.outputDirectory, "tile_rois.zip").getAbsolutePath());
}
else {
// Display our rois
rm.runCommand("Show All");
// Activate the RoiPicker tool
Toolbar bar = Toolbar.getInstance();
int roiPickerId = bar.getToolId(new RoiPicker().getToolName());
if (roiPickerId >= 0) {
bar.setTool(roiPickerId);
}
else {
IJ.runPlugIn(RoiPicker.class.getName(), "");
}
}
}
}
// close all images
for ( final ImageCollectionElement element : elements )
element.close();
}
/**
* Generates a ROI for each tile in the list of optimized images. The
* fusedImage is the resultant on which the ROIs will be drawn. The offset
* is a global offset to 0,0 for the upper leftmost tile.
*/
protected void generateRois(double[] offsets, ArrayList<ImagePlusTimePoint> optimizedImages)
{
IJ.showStatus("Generating ROIs from image tiles...");
RoiManager rm = RoiManager.getInstance();
if (rm == null) rm = new RoiManager();
// we'll make a map of rois to their ImageStack slice #, allowing them
// to be added to the RoiManager in the correct order.
Map<Integer, List<Roi>> roisBySlice = new HashMap<Integer, List<Roi>>();
// This reader is used to determine associations between tiles and files on disk
IFormatReader reader = null;
// Generate ROIs
for (int i=0; i<optimizedImages.size(); i++) {
// Each element of optimizedImages is assumed, for a given zct, to be part
// of the same tile (slice)
ImagePlusTimePoint iptp = optimizedImages.get(i);
reader = initializeReader(reader, iptp.getElement().getFile().getAbsolutePath());
int sizeZ = reader.getSizeZ();
int sizeT = reader.getSizeT();
int sizeC = reader.getSizeC();
// Skip any .xml, .cfg, etc... when looking up the image names
String[] seriesFiles = reader.getSeriesUsedFiles(true);
final int pixelOffset = seriesFiles == null ? 0 : seriesFiles.length;
// Assume that each series correlates to an element of optimizedImages
if (reader.getSeriesCount() > 1) {
reader.setSeries(i);
}
seriesFiles = reader.getSeriesUsedFiles();
ImagePlus unfused = iptp.getImagePlus();
// ROI/ImageJ slice number
int slice = 1;
// compute the x,y coordinates within this slice
double[] coords = new double[iptp.getElement().getDimensionality()];
iptp.getModel().applyInPlace(coords);
for (int j=0; j<offsets.length; j++) {
coords[j] -= offsets[j];
}
int coordXOffset = (int) Math.floor(coords[0]);
int coordYOffset = (int) Math.floor(coords[1]);
for (int t = 0; t < sizeT; t++) {
for (int z = 0; z < sizeZ; z++) {
for (int c = 0; c < sizeC; c++) {
Roi roi =
new Roi(coordXOffset, coordYOffset, unfused.getWidth(), unfused
.getHeight());
// set roi name and position
roi.setPosition(c + 1, z + 1, t + 1);
String roiName =
"sp=" + slice + "; label=" + i + "; series=" +
reader.getSeries() + "; C=" + (c + 1) + "; Z=" + (z + 1) + "; T=" + (t + 1);
if (reader != null) {
String sourceName = "unknown file " + reader.getIndex(z, c, t);
if (seriesFiles != null &&
seriesFiles.length > reader.getIndex(z, c, t) + pixelOffset)
{
sourceName =
new File(seriesFiles[reader.getIndex(z, c, t) + pixelOffset]).getName();
}
roiName += "; file=" + sourceName;
}
roi.setName(roiName);
if (roisBySlice.get(slice) == null) roisBySlice.put(slice,
new ArrayList<Roi>());
// index the roi to be added later to the RoiManager
roisBySlice.get(slice).add(roi);
slice++;
}
}
}
}
try {
if (reader != null) reader.close();
}
catch (IOException e) {
Log.error("Failed to close Bio-Formats reader.");
}
Log.info("Adding ROIs...");
List<Integer> keys = new ArrayList<Integer>(roisBySlice.keySet());
Collections.sort(keys);
for (Integer slice : keys) {
// HACK..
// rm.add annoyingly puts a 0 at the end of each label. But if using
// RoiManager.addRoi, only the first slice's rois are added (even if
// updating the fusedImage's position).
for (Roi roi : roisBySlice.get(slice))
rm.add((ImagePlus)null, roi, 0);
}
Log.info("ROIs generated.");
}
/**
* Initializes an {@link ImageReader} if the provided reader is null, or
* does not match the given file id.
* <p>
* NB: All exceptions are handled in this method. If an exception is caught,
* null will be returned.
* </p>
*/
protected IFormatReader initializeReader(IFormatReader in, final String file)
{
Log.info("Initializing Bio-Formats reader...");
if (in == null || !file.equalsIgnoreCase(in.getCurrentFile())) {
if (in != null) {
try {
in.close();
}
catch (IOException e) {
Log.error("Failed to close Bio-Formats reader.");
return null;
}
}
in = new ImageReader();
final IMetadata omeMeta = MetadataTools.createOMEXMLMetadata();
in.setMetadataStore(omeMeta);
try {
in.setId(file);
}
catch (FormatException e) {
Log.error("Failed to discover file names. FormatException when parsing: " +
file);
return null;
}
catch (IOException e) {
Log.error("Failed to discover file names. IOException when parsing: " +
file);
return null;
}
}
return in;
}
protected ImagePlus[] openBF( String multiSeriesFileName, boolean splitC,
boolean splitT, boolean splitZ, boolean autoScale, boolean crop,
boolean allSeries )
{
ImporterOptions options;
ImagePlus[] imps = null;
try
{
options = new ImporterOptions();
options.setId( new File( multiSeriesFileName ).getAbsolutePath() );
options.setSplitChannels( splitC );
options.setSplitTimepoints( splitT );
options.setSplitFocalPlanes( splitZ );
options.setAutoscale( autoScale );
options.setStackFormat(ImporterOptions.VIEW_HYPERSTACK);
options.setStackOrder(ImporterOptions.ORDER_XYCZT);
options.setCrop( crop );
options.setOpenAllSeries( allSeries );
imps = BF.openImagePlus( options );
}
catch (Exception e)
{
Log.error( "Cannot open multiseries file: " + e , e );
return null;
}
return imps;
}
protected ImagePlus[] openBFDefault( String multiSeriesFileName )
{
return openBF(multiSeriesFileName, false, false, false, false, false, true);
}
protected ArrayList< ImageCollectionElement > getLayoutFromMultiSeriesFile( final String multiSeriesFile, final double increaseOverlap, final boolean ignoreCalibration, final boolean invertX, final boolean invertY, final boolean ignoreZStage, final Downsampler ds )
{
if ( multiSeriesFile == null || multiSeriesFile.length() == 0 )
{
Log.error( "Filename is empty!" );
return null;
}
final ArrayList< ImageCollectionElement > elements = new ArrayList< ImageCollectionElement >();
final IFormatReader r = new ChannelSeparator();
final boolean timeHack;
try
{
final ServiceFactory factory = new ServiceFactory();
final OMEXMLService service = factory.getInstance( OMEXMLService.class );
final IMetadata meta = service.createOMEXMLMetadata();
r.setMetadataStore( meta );
r.setId( multiSeriesFile );
final int numSeries = r.getSeriesCount();
Log.debug( "numSeries: " + numSeries );
// get maxZ
int dim = 2;
for ( int series = 0; series < numSeries; ++series )
if ( r.getSizeZ() > 1 )
dim = 3;
Log.debug( "dim: " + dim );
final MetadataRetrieve retrieve = service.asRetrieve(r.getMetadataStore());
Log.debug( "retrieve: " + retrieve );
// CTR HACK: In the case of a single series, we treat each time point
// as a separate series for the purpose of stitching tiles.
timeHack = numSeries == 1;
for ( int series = 0; series < numSeries; ++series )
{
Log.debug( "fetching data for series: " + series );
r.setSeries( series );
final int sizeT = r.getSizeT();
Log.debug( "sizeT: " + sizeT );
final int maxT = timeHack ? sizeT : 1;
for ( int t = 0; t < maxT; ++t )
{
double[] location =
CommonFunctions.getPlanePosition( r, retrieve, series, t, invertX, invertY, ignoreZStage );
double locationX = location[0];
double locationY = location[1];
double locationZ = location[2];
if ( !ignoreCalibration )
{
// calibration
double calX = 1, calY = 1, calZ = 1;
Length cal;
final String dimOrder = r.getDimensionOrder().toUpperCase();
final int posX = dimOrder.indexOf( 'X' );
cal = retrieve.getPixelsPhysicalSizeX( series );
if ( posX >= 0 && cal != null && cal.value().doubleValue() != 0 )
calX = cal.value().doubleValue();
Log.debug( "calibrationX: " + calX );
final int posY = dimOrder.indexOf( 'Y' );
cal = retrieve.getPixelsPhysicalSizeY( series );
if ( posY >= 0 && cal != null && cal.value().doubleValue() != 0 )
calY = cal.value().doubleValue();
Log.debug( "calibrationY: " + calY );
final int posZ = dimOrder.indexOf( 'Z' );
cal = retrieve.getPixelsPhysicalSizeZ( series );
if ( posZ >= 0 && cal != null && cal.value().doubleValue() != 0 )
calZ = cal.value().doubleValue();
Log.debug( "calibrationZ: " + calZ );
// location in pixel values;
locationX /= calX;
locationY /= calY;
locationZ /= calZ;
}
// increase overlap if desired
locationX *= (100.0-increaseOverlap)/100.0;
locationY *= (100.0-increaseOverlap)/100.0;
locationZ *= (100.0-increaseOverlap)/100.0;
// create ImageInformationList
final ImageCollectionElement element;
if ( dim == 2 )
{
element = new ImageCollectionElement( new File( multiSeriesFile ), elements.size() );
element.setModel( new TranslationModel2D() );
element.setOffset( new float[]{ (float)locationX, (float)locationY } );
element.setDimensionality( 2 );
}
else
{
element = new ImageCollectionElement( new File( multiSeriesFile ), elements.size() );
element.setModel( new TranslationModel3D() );
element.setOffset( new float[]{ (float)locationX, (float)locationY, (float)locationZ } );
element.setDimensionality( 3 );
}
elements.add( element );
}
}
}
catch ( Exception ex )
{
Log.error(ex);
return null;
}
// open all images
ImporterOptions options;
try
{
options = new ImporterOptions();
options.setId( new File( multiSeriesFile ).getAbsolutePath() );
options.setSplitChannels( false );
options.setSplitTimepoints( timeHack );
options.setSplitFocalPlanes( false );
options.setAutoscale( false );
options.setStackFormat(ImporterOptions.VIEW_HYPERSTACK);
options.setStackOrder(ImporterOptions.ORDER_XYCZT);
options.setCrop(false);
options.setOpenAllSeries( true );
final ImagePlus[] imps = BF.openImagePlus( options );
if ( ds != null ) {
ds.getInput(imps[0].getWidth(), imps[0].getHeight());
ds.run(imps);
ds.run(elements);
}
if ( imps.length != elements.size() )
{
Log.error( "Inconsistent series layout. Metadata says " + elements.size() + " tiles, but contains only " + imps.length + " images/tiles." );
for ( ImagePlus imp : imps )
if ( imp != null )
imp.close();
return null;
}
for ( int series = 0; series < elements.size(); ++series )
{
final ImageCollectionElement element = elements.get( series );
element.setImagePlus( imps[ series ] ); // assign the sub-series to the elements list