-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathFusionTools.java
More file actions
1288 lines (1084 loc) · 44.5 KB
/
Copy pathFusionTools.java
File metadata and controls
1288 lines (1084 loc) · 44.5 KB
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
/*-
* #%L
* Software for the reconstruction of multi-view microscopic acquisitions
* like Selective Plane Illumination Microscopy (SPIM) Data.
* %%
* Copyright (C) 2012 - 2024 Multiview Reconstruction developers.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
package net.preibisch.mvrecon.process.fusion;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Vector;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import bdv.util.ConstantRandomAccessible;
import ij.IJ;
import ij.ImagePlus;
import mpicbg.models.AffineModel1D;
import mpicbg.spim.data.generic.AbstractSpimData;
import mpicbg.spim.data.generic.sequence.AbstractSequenceDescription;
import mpicbg.spim.data.generic.sequence.BasicImgLoader;
import mpicbg.spim.data.generic.sequence.BasicViewDescription;
import mpicbg.spim.data.registration.ViewRegistration;
import mpicbg.spim.data.sequence.Angle;
import mpicbg.spim.data.sequence.Channel;
import mpicbg.spim.data.sequence.Illumination;
import mpicbg.spim.data.sequence.ImgLoader;
import mpicbg.spim.data.sequence.TimePoint;
import mpicbg.spim.data.sequence.ViewDescription;
import mpicbg.spim.data.sequence.ViewId;
import mpicbg.spim.data.sequence.VoxelDimensions;
import net.imglib2.Cursor;
import net.imglib2.Dimensions;
import net.imglib2.FinalInterval;
import net.imglib2.Interval;
import net.imglib2.IterableInterval;
import net.imglib2.RandomAccess;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.cache.CacheLoader;
import net.imglib2.cache.img.RandomAccessibleCacheLoader;
import net.imglib2.cache.img.ReadOnlyCachedCellImgFactory;
import net.imglib2.cache.img.ReadOnlyCachedCellImgOptions;
import net.imglib2.cache.img.optional.CacheOptions.CacheType;
import net.imglib2.converter.Converters;
import net.imglib2.converter.RealTypeConverters;
import net.imglib2.img.Img;
import net.imglib2.img.ImgFactory;
import net.imglib2.img.basictypeaccess.AccessFlags;
import net.imglib2.img.basictypeaccess.array.ArrayDataAccess;
import net.imglib2.img.cell.Cell;
import net.imglib2.img.cell.CellGrid;
import net.imglib2.img.imageplus.ImagePlusImgFactory;
import net.imglib2.realtransform.AffineTransform3D;
import net.imglib2.type.NativeType;
import net.imglib2.type.Type;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.real.FloatType;
import net.imglib2.util.Cast;
import net.imglib2.util.Pair;
import net.imglib2.util.RealSum;
import net.imglib2.util.Util;
import net.imglib2.util.ValuePair;
import net.imglib2.view.Views;
import net.preibisch.legacy.io.IOFunctions;
import net.preibisch.mvrecon.Threads;
import net.preibisch.mvrecon.fiji.plugin.fusion.FusionGUI.FusionType;
import net.preibisch.mvrecon.fiji.spimdata.SpimData2;
import net.preibisch.mvrecon.fiji.spimdata.ViewSetupUtils;
import net.preibisch.mvrecon.fiji.spimdata.explorer.popup.DisplayFusedImagesPopup;
import net.preibisch.mvrecon.process.boundingbox.BoundingBoxMaximal;
import net.preibisch.mvrecon.process.downsampling.DownsampleTools;
import net.preibisch.mvrecon.process.export.DisplayImage;
import net.preibisch.mvrecon.process.fusion.intensityadjust.IntensityAdjuster;
import net.preibisch.mvrecon.process.fusion.lazy.LazyFusionTools;
import net.preibisch.mvrecon.process.fusion.transformed.FusedRandomAccessibleInterval;
import net.preibisch.mvrecon.process.fusion.transformed.FusedRandomAccessibleInterval.Fusion;
import net.preibisch.mvrecon.process.fusion.transformed.TransformView;
import net.preibisch.mvrecon.process.fusion.transformed.TransformVirtual;
import net.preibisch.mvrecon.process.fusion.transformed.TransformWeight;
import net.preibisch.mvrecon.process.fusion.transformed.weightcombination.CombineWeightsRandomAccessibleInterval;
import net.preibisch.mvrecon.process.fusion.transformed.weightcombination.CombineWeightsRandomAccessibleInterval.CombineType;
import net.preibisch.mvrecon.process.fusion.transformed.weights.ContentBasedRealRandomAccessible;
import net.preibisch.mvrecon.process.interestpointregistration.TransformationTools;
import net.preibisch.mvrecon.process.interestpointregistration.pairwise.constellation.grouping.Group;
public class FusionTools
{
public static enum ImgDataType { VIRTUAL, CACHED, PRECOMPUTED };
public static String[] imgDataTypeChoice = new String[]{ "Virtual", "Cached", "Precompute Image" }; // still needed for deconvolution
public static float defaultBlendingRange = 40;
public static float defaultBlendingBorder = 0;
public static double defaultContentBasedSigma1 = 20;
public static double defaultContentBasedSigma2 = 40;
public static long numPixels( final Interval bb, final double downsampling )
{
final long[] min = new long[ bb.numDimensions() ];
final long[] max = new long[ bb.numDimensions() ];
bb.min( min );
bb.max( max );
return numPixels( min, max, downsampling );
}
public static long numPixels( final long[] dim, final double downsampling )
{
final long[] min = new long[ dim.length ];
final long[] max = new long[ dim.length ];
for ( int d = 0; d < dim.length; ++d )
{
min[ d ] = 0;
max[ d ] = dim[ d ] - 1;
}
return numPixels( min, max, downsampling );
}
public static long numPixels( final long[] min, final long[] max, final double downsampling )
{
final double ds;
if ( Double.isNaN( downsampling ) )
ds = 1;
else
ds = downsampling;
long numpixels = 1;
for ( int d = 0; d < min.length; ++d )
numpixels *= Math.max( 1, Math.round( (max[ d ] - min[ d ] + 1)/ds ) );
return numpixels;
}
/**
* Virtually fuses views using a maximal bounding box around all views
*
* @param spimData - an AbstractSpimData object
* @param viewIds - which viewIds to fuse (be careful to remove not present one's first)
* @param fusionType - how to combine pixels
*
* @return a virtually fused zeroMin RandomAccessibleInterval and the transformation to map it to global coordinates
*/
public static RandomAccessibleInterval< FloatType > fuseVirtual(
final AbstractSpimData< ? extends AbstractSequenceDescription< ?, ?, ? extends ImgLoader > > spimData,
final Collection< ? extends ViewId > viewIds,
final FusionType fusionType )
{
return fuseVirtual(
spimData,
viewIds,
fusionType,
new BoundingBoxMaximal( viewIds, spimData ).estimate( "Full Bounding Box" ),
null );
}
/**
* Virtually fuses views using a maximal bounding box around all views
*
* @param spimData - an AbstractSpimData object
* @param viewIds - which viewIds to fuse (be careful to remove not present one's first)
* @param adjustIntensities - adjust intensities according to whats stored in the spimdata
* @param fusionType - how to combine pixels
* @return a virtually fused zeroMin RandomAccessibleInterval
*/
public static RandomAccessibleInterval< FloatType > fuseVirtual(
final SpimData2 spimData,
final Collection< ? extends ViewId > viewIds,
final FusionType fusionType,
final boolean adjustIntensities )
{
return fuseVirtual(
spimData,
viewIds,
fusionType,
new BoundingBoxMaximal( viewIds, spimData ).estimate( "Full Bounding Box" ),
adjustIntensities ? spimData.getIntensityAdjustments().getIntensityAdjustments() : null );
}
/**
* Virtually fuses views
*
* @param imgloader - an imgloader
* @param registrations - all (updated) registrations
* @param viewDescriptions - all viewdescriptions
* @param views - which viewIds to fuse (be careful to remove not present one's first)
* @param fusionType - how to combine pixels
* @param bb - the bounding box in world coordinates (can be loaded from XML or defined through one of the BoundingBoxEstimation implementations)
*
* @return a virtually fused zeroMin RandomAccessibleInterval and the transformation to map it to global coordinates
*/
public static RandomAccessibleInterval< FloatType > fuseVirtual(
final BasicImgLoader imgloader,
final Map< ViewId, ? extends AffineTransform3D > registrations, // now contain the downsampling already
final Map< ViewId, ? extends BasicViewDescription< ? > > viewDescriptions,
final Collection< ? extends ViewId > views,
final FusionType fusionType,
final Interval bb )
{
return fuseVirtual( imgloader, registrations, viewDescriptions, views, fusionType, 1, FusionTools.defaultBlendingRange, bb, null );
}
/**
* Virtually fuses views
*
* @param spimData - an AbstractSpimData object
* @param viewIds - which viewIds to fuse (be careful to remove not present one's first)
* @param fusionType - how to combine pixels
* @param bb - the bounding box in world coordinates (can be loaded from XML or defined through one of the BoundingBoxEstimation implementations)
*
* @return a virtually fused zeroMin RandomAccessibleInterval and the transformation to map it to global coordinates
*/
public static RandomAccessibleInterval< FloatType > fuseVirtual(
final AbstractSpimData< ? > spimData,
final Collection< ? extends ViewId > viewIds,
final FusionType fusionType,
final Interval bb )
{
return fuseVirtual( spimData, viewIds, fusionType, bb, null );
}
/**
* Virtually fuses views
*
* @param spimData - an AbstractSpimData object
* @param viewIds - which viewIds to fuse (be careful to remove not present one's first)
* @param fusionType - how to combine pixels
* @param bb - the bounding box in world coordinates (can be loaded from XML or defined through one of the BoundingBoxEstimation implementations)
* @param intensityAdjustments - the intensityadjustsments or null
*
* @return a virtually fused zeroMin RandomAccessibleInterval
*/
public static RandomAccessibleInterval< FloatType > fuseVirtual(
final AbstractSpimData< ? > spimData,
final Collection< ? extends ViewId > viewIds,
final FusionType fusionType,
final Interval bb,
final Map< ? extends ViewId, AffineModel1D > intensityAdjustments )
{
return fuseVirtual( spimData, viewIds, fusionType, 1, FusionTools.defaultBlendingRange, bb, intensityAdjustments );
}
public static RandomAccessibleInterval< FloatType > fuseVirtual(
final AbstractSpimData< ? > spimData,
final Collection< ? extends ViewId > views,
final FusionType fusionType,
final int interpolation,
final float blendingRange,
final Interval boundingBox,
final Map< ? extends ViewId, AffineModel1D > intensityAdjustments )
{
final BasicImgLoader imgLoader = spimData.getSequenceDescription().getImgLoader();
final HashMap< ViewId, AffineTransform3D > registrations = new HashMap<>();
for ( final ViewId viewId : views )
{
final ViewRegistration vr = spimData.getViewRegistrations().getViewRegistration( viewId );
vr.updateModel();
registrations.put( viewId, vr.getModel().copy() );
}
final Map< ViewId, ? extends BasicViewDescription< ? > > viewDescriptions = spimData.getSequenceDescription().getViewDescriptions();
return fuseVirtual( imgLoader, registrations, viewDescriptions, views, fusionType, interpolation, blendingRange, boundingBox, intensityAdjustments );
}
/**
* Creates an anisotropic bounding box by floor/ceil to include all data and provides the affine transformation to scale it to global coordinates
*
* @param boundingBox - the bounding box to scale
* @param anisotropy - the desired anisotropy
* @return a downsampled interval and the corresponding affine transform to map it to global coordinates or a copy if anisotropy == Double.NaN or 1.0
*/
public static Pair< Interval, AffineTransform3D > createAnisotropicBoundingBox(
final Interval boundingBox,
final double anisotropy )
{
if ( Double.isNaN( anisotropy ) || anisotropy == 1.0 )
return new ValuePair<>( new FinalInterval( boundingBox ), new AffineTransform3D() );
final long[] min = boundingBox.minAsLongArray();
final long[] max = boundingBox.maxAsLongArray();
final double minValue = min[ 2 ] / anisotropy;
min[ 2 ] = Math.round( Math.floor( minValue ) );
max[ 2 ] = Math.round( Math.ceil( max[ 2 ] / anisotropy ) );
final AffineTransform3D t = new AffineTransform3D();
t.scale( 1, 1, anisotropy );
t.translate( 0, 0, ( minValue - min[ 2 ] ) * anisotropy );
return new ValuePair<>( new FinalInterval( min, max ), t );
}
/**
* Creates a downsampled bounding box by rounding and provides the affine transformation to scale it to global coordinates, which also corrects
* for the fact that the fused image is ZEROMIN (TODO: change that)
*
* @param boundingBox - the bounding box to scale
* @param downsampling - the desired downsampling
* @return a downsampled interval and the corresponding affine transform to map it to global coordinates or a copy if downsampling == Double.NaN or 1.0
*/
public static Pair< Interval, AffineTransform3D > createDownsampledBoundingBox(
final Interval boundingBox,
final double downsampling )
{
if ( Double.isNaN( downsampling ) || downsampling == 1.0 )
return new ValuePair<>( new FinalInterval( boundingBox ), new AffineTransform3D() );
// TODO: Note, I recently changed this code so the offset is being computed (22/12/29)
// there is rounding when scaling the bounding box ...
final double[] offset = new double[ boundingBox.numDimensions() ];
final Interval bbDS = TransformVirtual.scaleBoundingBox( boundingBox, 1.0 / downsampling, offset );
final double[] translation = new double[ boundingBox.numDimensions() ];
for ( int d = 0; d < offset.length; ++d )
translation[ d ] = ( offset[ d ] + bbDS.min( d ) ) * downsampling;
// the virtual image is zeroMin, this transformation puts it into the global coordinate system
final AffineTransform3D t = new AffineTransform3D();
t.scale( downsampling );
t.translate( translation );
return new ValuePair<>( bbDS, t );
}
public static Interval getFusedZeroMinInterval( final Interval bbDS )
{
final long[] dim = new long[ bbDS.numDimensions() ];
bbDS.dimensions( dim );
return new FinalInterval( dim );
}
public static boolean is2d( final Collection< ? extends BasicViewDescription< ? > > views )
{
// go through the images and check if they are all 2-dimensional
boolean is2d = false;
for ( final BasicViewDescription< ? > vd: views )
{
if ( vd.getViewSetup().hasSize() )
{
if ( vd.getViewSetup().getSize().dimension(2) == 1)
is2d = true;
else
{
// TODO: maybe warn that 2d images will be lost during fusion if we have a 2d/3d mixup
is2d = false; // we found a non-2d image
break;
}
}
}
return is2d;
}
public static RandomAccessibleInterval< FloatType > fuseVirtual(
final BasicImgLoader imgloader,
final Map< ViewId, ? extends AffineTransform3D > registrations, // now contain the downsampling already
final Map< ViewId, ? extends BasicViewDescription< ? > > viewDescriptions,
final Collection< ? extends ViewId > views,
final FusionType fusionType, // see FusionGUI.fusionTypes[]{"Avg", "Avg, Blending", "Avg, Content Based", "Avg, Blending & Content Based", "Max", "First Tile Wins"}
final int interpolation,
final float blendingRange,
final Interval boundingBox, // is already downsampled
//final double downsampling,
final Map< ? extends ViewId, AffineModel1D > intensityAdjustments )
{
// go through the views and check if they are all 2-dimensional
final boolean is2d = is2d( views.stream().map( v -> viewDescriptions.get( v ) ).collect( Collectors.toList() ) );
final Interval bb, bBox2d;
if (is2d)
{
// set the translational part of the registrations to 0
for ( AffineTransform3D transform : registrations.values())
{
// check if we have just scaling in 3d
boolean justScale3d = true;
for (int d1 = 0; d1<3; d1++)
for (int d2 = 0; d2<3; d2++)
if ((d1 > 1 || d2>1) && d1 != d2 && transform.get(d1,d2) != 0)
justScale3d = false;
if (justScale3d)
transform.set(0,2,3);
else
IOFunctions.println("WARNING: You are trying to fuse 2d images with 3d registrations.");
}
// create a virtual 2-d bounding box
long[] bbMin = new long[3];
long[] bbMax = new long[3];
boundingBox.min(bbMin);
boundingBox.max(bbMax);
bbMin[2] = bbMax[2] = 0;
bBox2d = new FinalInterval(bbMin, bbMax);
bb = bBox2d;
}
else
{
bBox2d = null;
bb = boundingBox;
}
/*
final Pair< Interval, AffineTransform3D > scaledBB = createDownsampledBoundingBox( is_2d ? bBox2d : boundingBox, downsampling );
final Interval bb = scaledBB.getA();
final AffineTransform3D bbTransform = scaledBB.getB();
*/
// which views to process (use un-altered bounding box and registrations)
final ArrayList< ViewId > viewIdsToProcess =
LazyFusionTools.overlappingViewIds(
bb,
views,
registrations,
LazyFusionTools.assembleDimensions( views, viewDescriptions ),
LazyFusionTools.defaultAffineExpansion );
// nothing to save...
if ( viewIdsToProcess.size() == 0 )
{
final RandomAccessibleInterval< FloatType > fused =
Views.interval(
new ConstantRandomAccessible< FloatType >( new FloatType( 0 ), 3 ),
new FinalInterval( getFusedZeroMinInterval( bb ) ) );
//return new ValuePair<>( fused, bbTransform );
return fused;
}
final ArrayList< RandomAccessibleInterval< FloatType > > images = new ArrayList<>();
final ArrayList< RandomAccessibleInterval< FloatType > > weights = new ArrayList<>();
// to be able to use the "lowest ViewId" wins strategy
Collections.sort( viewIdsToProcess );
for ( final ViewId viewId : viewIdsToProcess )
{
final AffineTransform3D model = registrations.get( viewId ).copy();
/*
if ( !Double.isNaN( downsampling ) )
{
model = model.copy();
TransformVirtual.scaleTransform( model, 1.0 / downsampling );
}
*/
// this modifies the model so it maps from a smaller image to the global coordinate space,
// which applies for the image itself as well as the weights since they also use the smaller
// input image as reference
final double[] usedDownsampleFactors = new double[ 3 ];
RandomAccessibleInterval inputImg = DownsampleTools.openDownsampled( imgloader, viewId, model, usedDownsampleFactors );
if ( intensityAdjustments != null && intensityAdjustments.containsKey( viewId ) )
inputImg = Converters.convert(
convertInput( inputImg ),
new IntensityAdjuster( intensityAdjustments.get( viewId ) ),
new FloatType() );
images.add( TransformView.transformView( inputImg, model, bb, 0, interpolation ) );
// add all (or no) weighting schemes
if ( fusionType == FusionType.AVG_BLEND || fusionType == FusionType.AVG_BLEND_CONTENT || fusionType == FusionType.AVG_CONTENT )
{
RandomAccessibleInterval< FloatType > transformedBlending = null, transformedContentBased = null;
// instantiate blending if necessary
if ( fusionType == FusionType.AVG_BLEND || fusionType == FusionType.AVG_BLEND_CONTENT )
{
final float[] blending = Util.getArrayFromValue( blendingRange, 3 );
final float[] border = Util.getArrayFromValue( defaultBlendingBorder, 3 );
// TODO: this is wrong, since the blending is applied to the input images
// it must only depend on the scale factor that the input images were opened with
// TODO: NO, it not wrong here, the assumption is that the defaultBlendingRange should
// should be achieved in the output image (independent of the downsampling
// adjust both for z-scaling (anisotropy), downsampling, and registrations itself
adjustBlending( viewDescriptions.get( viewId ), blending, border, model );
//System.out.println( "Adjusted blending range: " + Util.printCoordinates( blending ) );
transformedBlending = TransformWeight.transformBlending( new FinalInterval( inputImg ), border, blending, model, bb );
}
// instantiate content based if necessary
if ( fusionType == FusionType.AVG_BLEND_CONTENT || fusionType == FusionType.AVG_CONTENT )
{
final double[] sigma1 = Util.getArrayFromValue( defaultContentBasedSigma1, 3 );
final double[] sigma2 = Util.getArrayFromValue( defaultContentBasedSigma2, 3 );
// TODO: this is wrong, since the blending is applied to the input images
// it must only depend on the scale factor that the input images were opened with
// TODO: yes, here it is wrong ...
// adjust both for z-scaling (anisotropy), downsampling, and registrations itself
adjustContentBased( viewDescriptions.get( viewId ), sigma1, sigma2, usedDownsampleFactors );
//System.out.println( "Adjusted content based sigma1=" + Util.printCoordinates( sigma1 ) + " , sigma2="+ Util.printCoordinates( sigma2 ));
// TODO: compute content-based only for the area around the block that is being fused
transformedContentBased = TransformWeight.transformContentBased( inputImg, sigma1, sigma2, LazyFusionTools.defaultBlockSize3d, ContentBasedRealRandomAccessible.defaultScale, model, bb );
}
if ( fusionType == FusionType.AVG_BLEND_CONTENT )
{
weights.add( new CombineWeightsRandomAccessibleInterval(
new FinalInterval( transformedBlending ),
transformedBlending,
transformedContentBased,
CombineType.MUL ) );
}
else if ( fusionType == FusionType.AVG_BLEND )
{
weights.add( transformedBlending );
}
else if ( fusionType == FusionType.AVG_CONTENT )
{
weights.add( transformedContentBased );
}
}
else
{
final RandomAccessibleInterval< FloatType > imageArea =
Views.interval( new ConstantRandomAccessible< FloatType >( new FloatType( 1 ), 3 ), new FinalInterval( inputImg ) );
weights.add( TransformView.transformView( imageArea, model, bb, 0, 0 ) );
}
}
final Fusion fusion;
if ( fusionType == FusionType.AVG || fusionType == FusionType.AVG_BLEND || fusionType == FusionType.AVG_BLEND_CONTENT || fusionType == FusionType.AVG_CONTENT )
fusion = Fusion.AVG;
else if ( fusionType == FusionType.MAX )
fusion = Fusion.MAX;
else
fusion = Fusion.FIRST_WINS;
return new FusedRandomAccessibleInterval( new FinalInterval( getFusedZeroMinInterval( bb ) ), fusion, images, weights );
//return new ValuePair<>( new FusedRandomAccessibleInterval( new FinalInterval( getFusedZeroMinInterval( bb ) ), images, weights ), bbTransform );
}
public static < T extends RealType< T > > RandomAccessibleInterval< FloatType > convertInput( final RandomAccessibleInterval< T > img )
{
return img.getType() instanceof FloatType
? Cast.unchecked( img )
: RealTypeConverters.convert( img, new FloatType() );
}
public static ImagePlus displayVirtually( final RandomAccessibleInterval< FloatType > input )
{
return display( input, ImgDataType.VIRTUAL, DisplayFusedImagesPopup.cellDim, DisplayFusedImagesPopup.maxCacheSize );
}
public static ImagePlus displayVirtually( final RandomAccessibleInterval< FloatType > input, final double min, final double max )
{
return display( input, ImgDataType.VIRTUAL, min, max, DisplayFusedImagesPopup.cellDim, DisplayFusedImagesPopup.maxCacheSize );
}
public static ImagePlus displayCopy( final RandomAccessibleInterval< FloatType > input )
{
return display( input, ImgDataType.PRECOMPUTED, DisplayFusedImagesPopup.cellDim, DisplayFusedImagesPopup.maxCacheSize );
}
public static ImagePlus displayCopy( final RandomAccessibleInterval< FloatType > input, final double min, final double max )
{
return display( input, ImgDataType.PRECOMPUTED, min, max, DisplayFusedImagesPopup.cellDim, DisplayFusedImagesPopup.maxCacheSize );
}
public static ImagePlus displayCached(
final RandomAccessibleInterval< FloatType > input,
final int[] cellDim,
final int maxCacheSize )
{
return display( input, ImgDataType.CACHED, cellDim, maxCacheSize );
}
public static ImagePlus displayCached(
final RandomAccessibleInterval< FloatType > input,
final double min,
final double max,
final int[] cellDim,
final int maxCacheSize )
{
return display( input, ImgDataType.CACHED, min, max, cellDim, maxCacheSize );
}
public static ImagePlus displayCached( final RandomAccessibleInterval< FloatType > input )
{
return displayCached( input, DisplayFusedImagesPopup.cellDim, DisplayFusedImagesPopup.maxCacheSize );
}
public static ImagePlus displayCached( final RandomAccessibleInterval< FloatType > input, final double min, final double max )
{
return display( input, ImgDataType.CACHED, min, max, DisplayFusedImagesPopup.cellDim, DisplayFusedImagesPopup.maxCacheSize );
}
public static ImagePlus display(
final RandomAccessibleInterval< FloatType > input,
final ImgDataType imgType )
{
return display( input, imgType, DisplayFusedImagesPopup.cellDim, DisplayFusedImagesPopup.maxCacheSize );
}
public static ImagePlus display(
final RandomAccessibleInterval< FloatType > input,
final ImgDataType imgType,
final int[] cellDim,
final int maxCacheSize )
{
return display( input, imgType, 0, 255, cellDim, maxCacheSize );
}
public static ImagePlus display(
final RandomAccessibleInterval< FloatType > input,
final ImgDataType imgType,
final double min,
final double max,
final int[] cellDim,
final int maxCacheSize )
{
final RandomAccessibleInterval< FloatType > img;
if ( imgType == ImgDataType.CACHED )
img = cacheRandomAccessibleInterval( input, maxCacheSize, new FloatType(), cellDim );
else if ( imgType == ImgDataType.PRECOMPUTED )
img = copyImg( input, new ImagePlusImgFactory<>(), new FloatType(), null, true );
else
img = input;
// set ImageJ title according to fusion type
final String title = imgType == ImgDataType.CACHED ?
"Fused, Virtual (cached) " : (imgType == ImgDataType.VIRTUAL ?
"Fused, Virtual" : "Fused" );
return DisplayImage.getImagePlusInstance( img, true, title, min, max );
}
/**
* Compute how much blending in the input has to be done so the target values blending and border are achieved in the fused image
*
* @param vd - which view
* @param blending - the target blending range, e.g. 40
* @param border - the target blending border, e.g. 0
* @param transformationModel - the transformation model used to map from the (downsampled) input to the output
*/
// NOTE (TP) blending and border are modified
public static void adjustBlending( final BasicViewDescription< ? > vd, final float[] blending, final float[] border, final AffineTransform3D transformationModel )
{
adjustBlending( vd.getViewSetup().getSize(), Group.pvid( vd ), blending, border, transformationModel );
}
public static void adjustBlending( final Dimensions dim, final String name, final float[] blending, final float[] border, final AffineTransform3D transformationModel )
{
final double[] scale = TransformationTools.scaling( dim, transformationModel ).getA();
final NumberFormat f = TransformationTools.f;
//System.out.println( "View " + name + " is currently scaled by: (" +
// f.format( scale[ 0 ] ) + ", " + f.format( scale[ 1 ] ) + ", " + f.format( scale[ 2 ] ) + ")" );
for ( int d = 0; d < blending.length; ++d )
{
blending[ d ] /= ( float )scale[ d ];
border[ d ] /= ( float )scale[ d ];
}
}
/**
* Compute how much sigma in the input has to be applied so the target values of sigma1 and 2 are achieved in the fused image
*
* @param vd - which view
* @param sigma1 - the target sigma1 for entropy approximation, e.g. 20
* @param sigma2 - the target sigma2 for entropy approximation, e.g. 40
* @param usedDownsampleFactors - the downsampling factors used to load the input image
*/
public static void adjustContentBased( final BasicViewDescription< ? > vd, final double[] sigma1, final double[] sigma2, final double[] usedDownsampleFactors )
{
for ( int d = 0; d < sigma1.length; ++d )
{
sigma1[ d ] /= ( float )usedDownsampleFactors[ d ];
sigma2[ d ] /= ( float )usedDownsampleFactors[ d ];
}
}
public static double getMinRes( final BasicViewDescription< ? > desc )
{
final VoxelDimensions size = ViewSetupUtils.getVoxelSize( desc.getViewSetup() );
if ( size == null )
{
IOFunctions.println( "(" + new Date(System.currentTimeMillis()) + "): WARNINIG, could not load voxel size!! Assuming 1,1,1" );
return 1;
}
return Math.min( size.dimension( 0 ), Math.min( size.dimension( 1 ), size.dimension( 2 ) ) );
}
public static String getIllumName( final List< Illumination > illumsToProcess )
{
String illumName = "_Ill" + illumsToProcess.get( 0 ).getName();
for ( int i = 1; i < illumsToProcess.size(); ++i )
illumName += "," + illumsToProcess.get( i ).getName();
return illumName;
}
public static String getAngleName( final List< Angle > anglesToProcess )
{
String angleName = "_Ang" + anglesToProcess.get( 0 ).getName();
for ( int i = 1; i < anglesToProcess.size(); ++i )
angleName += "," + anglesToProcess.get( i ).getName();
return angleName;
}
public static final ArrayList< ViewDescription > assembleInputData(
final SpimData2 spimData,
final TimePoint timepoint,
final Channel channel,
final List< ViewId > viewIdsToProcess )
{
final ArrayList< ViewDescription > inputData = new ArrayList< ViewDescription >();
for ( final ViewId viewId : viewIdsToProcess )
{
final ViewDescription vd = spimData.getSequenceDescription().getViewDescription(
viewId.getTimePointId(), viewId.getViewSetupId() );
if ( !vd.isPresent() || vd.getTimePointId() != timepoint.getId() || vd.getViewSetup().getChannel().getId() != channel.getId() )
continue;
// get the most recent model
spimData.getViewRegistrations().getViewRegistration( viewId ).updateModel();
inputData.add( vd );
}
return inputData;
}
public static < T extends NativeType< T > > RandomAccessibleInterval< T > cacheRandomAccessibleInterval(
final RandomAccessibleInterval< T > input,
final T type,
final int... cellDim )
{
return cacheRandomAccessibleInterval( input, -1, type, cellDim );
}
public static < T extends NativeType< T >, A extends ArrayDataAccess< A > > RandomAccessibleInterval< T > cacheRandomAccessibleInterval(
final RandomAccessibleInterval< T > input,
final long maxCacheSize,
final T type,
final int... cellDim )
{
final ReadOnlyCachedCellImgOptions options = ReadOnlyCachedCellImgOptions.options()
.cellDimensions( cellDim )
.cacheType( maxCacheSize > 0 ? CacheType.BOUNDED : CacheType.SOFTREF )
.maxCacheSize( maxCacheSize );
final ReadOnlyCachedCellImgFactory factory = new ReadOnlyCachedCellImgFactory( options );
final long[] dim = input.dimensionsAsLongArray();
final CacheLoader< Long, Cell< A > > loader = RandomAccessibleCacheLoader.get(
new CellGrid( dim, cellDim ),
input.view().zeroMin(),
AccessFlags.setOf( AccessFlags.VOLATILE ) );
final RandomAccessibleInterval<T> copy = factory.createWithCacheLoader( dim, type, loader );
return translateIfNecessary( input, copy );
}
public static < T extends Type< T > > RandomAccessibleInterval< T > copyImg( final RandomAccessibleInterval< T > input, final ImgFactory< T > factory, final T type, final ExecutorService service )
{
return copyImg( input, factory, type, service, false );
}
public static < T extends Type< T > > RandomAccessibleInterval< T > copyImg(
final RandomAccessibleInterval< T > input,
final ImgFactory< T > factory,
final T type,
final ExecutorService service,
final boolean showProgress )
{
return translateIfNecessary( input, copyImgNoTranslation( input, factory, type, service, showProgress ) );
}
public static < T extends Type< T > > Img< T > copyImgNoTranslation( final RandomAccessibleInterval< T > input, final ImgFactory< T > factory, final T type, final ExecutorService service )
{
return copyImgNoTranslation( input, factory, type, service, false );
}
public static < T extends Type< T > > Img< T > copyImgNoTranslation(
final RandomAccessibleInterval< T > input,
final ImgFactory< T > factory,
final T type,
final ExecutorService service,
final boolean showProgress )
{
final RandomAccessibleInterval< T > in;
if ( Views.isZeroMin( input ) )
in = input;
else
in = Views.zeroMin( input );
final long[] dim = new long[ in.numDimensions() ];
in.dimensions( dim );
final Img< T > tImg = factory.create( dim, type );
// copy the virtual construct into an actual image
copyImg( in, tImg, service, showProgress );
return tImg;
}
public static < T > RandomAccessibleInterval< T > translateIfNecessary( final Interval original, final RandomAccessibleInterval< T > copy )
{
if ( Views.isZeroMin( original ) )
{
return copy;
}
else
{
final long[] min = new long[ original.numDimensions() ];
original.min( min );
return Views.translate( copy, min );
}
}
public static < T extends Type< T > > void copyImg( final RandomAccessibleInterval< T > input, final RandomAccessibleInterval< T > output, final ExecutorService service )
{
copyImg( input, output, service, false );
}
public static < T extends Type< T > > void copyImg( final RandomAccessibleInterval< T > input, final RandomAccessibleInterval< T > output, final ExecutorService service, final boolean showProgress )
{
final long numPixels = Views.iterable( input ).size();
final int nThreads = Threads.numThreads();
final Vector< ImagePortion > portions = divideIntoPortions( numPixels );
final ArrayList< Callable< Void > > tasks = new ArrayList< Callable< Void > >();
final AtomicInteger progress = new AtomicInteger( 0 );
for ( final ImagePortion portion : portions )
{
tasks.add( new Callable< Void >()
{
@Override
public Void call() throws Exception
{
copyImg( portion.getStartPosition(), portion.getLoopSize(), input, output );
if ( showProgress )
IJ.showProgress( (double)progress.incrementAndGet() / tasks.size() );
return null;
}
});
}
if ( showProgress )
IJ.showProgress( 0.01 );
if ( service == null )
execTasks( tasks, nThreads, "copy image" );
else
execTasks( tasks, service, "copy image" );
}
public static final void execTasks( final ArrayList< Callable< Void > > tasks, final int nThreads, final String jobDescription )
{
final ExecutorService taskExecutor = Executors.newFixedThreadPool( nThreads );
execTasks( tasks, taskExecutor, jobDescription );
taskExecutor.shutdown();
}
public static final void execTasks( final ArrayList< Callable< Void > > tasks, final ExecutorService taskExecutor, final String jobDescription )
{
try
{
// invokeAll() returns when all tasks are complete
taskExecutor.invokeAll( tasks );
}
catch ( final InterruptedException e )
{
IOFunctions.println( "Failed to " + jobDescription + ": " + e );
e.printStackTrace();
return;
}
}
/*
* One thread of a method to compute the quotient between two images of the multiview deconvolution
*
* @param start
* @param loopSize
* @param source
* @param target
*/
public static final < T extends Type< T > > void copyImg(
final long start,
final long loopSize,
final RandomAccessibleInterval< T > source,
final RandomAccessibleInterval< T > target )
{
final IterableInterval< T > sourceIterable = Views.iterable( source );
final IterableInterval< T > targetIterable = Views.iterable( target );
if ( sourceIterable.iterationOrder().equals( targetIterable.iterationOrder() ) )
{
final Cursor< T > cursorSource = sourceIterable.cursor();
final Cursor< T > cursorTarget = targetIterable.cursor();
cursorSource.jumpFwd( start );
cursorTarget.jumpFwd( start );
for ( long l = 0; l < loopSize; ++l )
cursorTarget.next().set( cursorSource.next() );
}
else
{
final RandomAccess< T > raSource = source.randomAccess();
final Cursor< T > cursorTarget = targetIterable.localizingCursor();
cursorTarget.jumpFwd( start );
for ( long l = 0; l < loopSize; ++l )
{
cursorTarget.fwd();
raSource.setPosition( cursorTarget );
cursorTarget.get().set( raSource.get() );
}
}
}
public static < T extends RealType< T > > float[] minMax( final RandomAccessibleInterval< T > img )
{
final ExecutorService taskExecutor = Executors.newFixedThreadPool( Threads.numThreads() );
final float[] minmax = minMax(img, taskExecutor);
taskExecutor.shutdown();
return minmax;
}
public static < T extends RealType< T > > float[] minMax( final RandomAccessibleInterval< T > img, final ExecutorService service )
{
final IterableInterval< T > iterable = Views.iterable( img );
// split up into many parts for multithreading
final Vector< ImagePortion > portions = divideIntoPortions( iterable.size() );
// set up executor service
final ArrayList< Callable< float[] > > tasks = new ArrayList< Callable< float[] > >();
for ( final ImagePortion portion : portions )