forked from niivue/niivue-brainchop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
brainchop.js
3024 lines (2663 loc) · 125 KB
/
brainchop.js
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
import * as tf from '@tensorflow/tfjs'
import { BWLabeler } from './bwlabels.js'
export { runInference, inferenceModelsList, brainChopOpts }
const brainChopOpts = {
// General settings for input shape [batchSize, batch_D, batch_H, batch_W, numOfChan]
batchSize: 1, // How many batches are used during each inference iteration
numOfChan: 1, // num of channel of the input shape
isColorEnable: true, // If false, grey scale will enabled
isAutoColors: true, // If false, manualColorsRange will be in use
bgLabelValue: 0, // Semenatic Segmentation background label value
drawBoundingVolume: false, // plot bounding volume used to crop the brain
isBrainCropMaskBased: true, // Check if brain masking will be used for cropping & optional show or brain tissue will be used
showPhase1Output: false, // This will load to papaya the output of phase-1 (ie. brain mask or brain tissue)
isPostProcessEnable: true, // If true 3D Connected Components filter will apply
isContoursViewEnable: false, // If true 3D contours of the labeled regions will apply
browserArrayBufferMaxZDim: 30, // This value depends on Memory available
telemetryFlag: false, // Ethical and transparent collection of browser usage while adhering to security and privacy standards
chartXaxisStepPercent: 10, // percent from total labels on Xaxis
uiSampleName: 'BC_UI_Sample', // Sample name used by interface
atlasSelectedColorTable: 'Fire' // Select from ["Hot-and-Cold", "Fire", "Grayscale", "Gold", "Spectrum"]
}
// Inference Models, the ids must start from 1 in sequence
const inferenceModelsList = [
{
id: 1,
type: 'Segmentation',
path: './models/model5_gw_ae/model.json',
modelName: '\u26A1 Tissue GWM (light)',
labelsPath: './models/model5_gw_ae/labels.json',
colorsPath: './models/model5_gw_ae/colorLUT.json',
colormapPath: './models/model5_gw_ae/colormap3.json',
preModelId: null, // Model run first e.g. crop the brain { null, 1, 2, .. }
preModelPostProcess: false, // If true, perform postprocessing to remove noisy regions after preModel inference generate output.
isBatchOverlapEnable: false, // create extra overlap batches for inference
numOverlapBatches: 0, // Number of extra overlap batches for inference
enableTranspose: true, // Keras and tfjs input orientation may need a tranposing step to be matched
enableCrop: true, // For speed-up inference, crop brain from background before feeding to inference model to lower memory use.
cropPadding: 18, // Padding size add to cropped brain
autoThreshold: 0, // Threshold between 0 and 1, given no preModel and tensor is normalized either min-max or by quantiles. Will remove noisy voxels around brain
enableQuantileNorm: false, // Some models needs Quantile Normaliztion.
filterOutWithPreMask: false, // Can be used to multiply final output with premodel output mask to crean noisy areas
enableSeqConv: false, // For low memory system and low configuration, enable sequential convolution instead of last layer
textureSize: 0, // Requested Texture size for the model, if unknown can be 0.
warning: null, // Warning message to show when select the model.
inferenceDelay: 100, // Delay in ms time while looping layers applying.
description:
'Gray and white matter segmentation model. Operates on full T1 image in a single pass, but uses only 5 filters per layer. Can work on integrated graphics cards but is barely large enough to provide good accuracy. Still more accurate than the subvolume model.'
},
{
id: 2,
type: 'Segmentation',
path: './models/model20chan3cls/model.json',
modelName: '\u{1F52A} Tissue GWM (High Acc)',
labelsPath: './models/model20chan3cls/labels.json',
colorsPath: './models/model20chan3cls/colorLUT.json',
colormapPath: './models/model20chan3cls/colormap.json',
preModelId: null, // Model run first e.g. crop the brain { null, 1, 2, .. }
preModelPostProcess: false, // If true, perform postprocessing to remove noisy regions after preModel inference generate output.
isBatchOverlapEnable: false, // create extra overlap batches for inference
numOverlapBatches: 0, // Number of extra overlap batches for inference
enableTranspose: true, // Keras and tfjs input orientation may need a tranposing step to be matched
enableCrop: true, // For speed-up inference, crop brain from background before feeding to inference model to lower memory use.
cropPadding: 0, // Padding size add to cropped brain
autoThreshold: 0.2, // Threshold between 0 and 1, given no preModel and tensor is normalized either min-max or by quantiles. Will remove noisy voxels around brain
enableQuantileNorm: true, // Some models needs Quantile Normaliztion.
filterOutWithPreMask: false, // Can be used to multiply final output with premodel output mask to crean noisy areas
enableSeqConv: false, // For low memory system and low configuration, enable sequential convolution instead of last layer
textureSize: 0, // Requested Texture size for the model, if unknown can be 0.
warning:
"This model may need dedicated graphics card. For more info please check with Browser Resources <i class='fa fa-cogs'></i>.",
inferenceDelay: 100, // Delay in ms time while looping layers applying.
description:
'Gray and white matter segmentation model. Operates on full T1 image in a single pass but needs a dedicated graphics card to operate. Provides the best accuracy with hard cropping for better speed'
},
{
id: 3,
type: 'Segmentation',
path: './models/model20chan3cls/model.json',
modelName: '\u{1F52A} Tissue GWM (High Acc, Low Mem)',
labelsPath: './models/model20chan3cls/labels.json',
colorsPath: './models/model20chan3cls/colorLUT.json',
colormapPath: './models/model20chan3cls/colormap.json',
preModelId: null, // Model run first e.g. crop the brain { null, 1, 2, .. }
preModelPostProcess: false, // If true, perform postprocessing to remove noisy regions after preModel inference generate output.
isBatchOverlapEnable: false, // create extra overlap batches for inference
numOverlapBatches: 0, // Number of extra overlap batches for inference
enableTranspose: true, // Keras and tfjs input orientation may need a tranposing step to be matched
enableCrop: true, // For speed-up inference, crop brain from background before feeding to inference model to lower memory use.
cropPadding: 0, // Padding size add to cropped brain
autoThreshold: 0.2, // Threshold between 0 and 1, given no preModel and tensor is normalized either min-max or by quantiles. Will remove noisy voxels around brain
enableQuantileNorm: true, // Some models needs Quantile Normaliztion.
filterOutWithPreMask: false, // Can be used to multiply final output with premodel output mask to crean noisy areas
enableSeqConv: true, // For low memory system and low configuration, enable sequential convolution instead of last layer
textureSize: 0, // Requested Texture size for the model, if unknown can be 0.
warning:
"This model may need dedicated graphics card. For more info please check with Browser Resources <i class='fa fa-cogs'></i>.",
inferenceDelay: 100, // Delay in ms time while looping layers applying.
description:
'Gray and white matter segmentation model. Operates on full T1 image in a single pass but needs a dedicated graphics card to operate. Provides high accuracy and fit low memory available but slower'
},
{
id: 4,
type: 'Atlas',
path: './models/model30chan18cls/model.json',
modelName: '\u{1FA93} Subcortical + GWM (High Mem, Fast)',
labelsPath: './models/model30chan18cls/labels.json',
colorsPath: './models/model30chan18cls/colorLUT.json',
colormapPath: './models/model30chan18cls/colormap.json',
preModelId: null, // Model run first e.g. crop the brain { null, 1, 2, .. }
preModelPostProcess: false, // If true, perform postprocessing to remove noisy regions after preModel inference generate output.
isBatchOverlapEnable: false, // create extra overlap batches for inference
numOverlapBatches: 200, // Number of extra overlap batches for inference
enableTranspose: true, // Keras and tfjs input orientation may need a tranposing step to be matched
enableCrop: true, // For speed-up inference, crop brain from background before feeding to inference model to lower memory use.
cropPadding: 0, // Padding size add to cropped brain
autoThreshold: 0.2, // Threshold between 0 and 1, given no preModel and tensor is normalized either min-max or by quantiles. Will remove noisy voxels around brain
enableQuantileNorm: false, // Some models needs Quantile Normaliztion.
filterOutWithPreMask: false, // Can be used to multiply final output with premodel output mask to crean noisy areas
enableSeqConv: false, // For low memory system and low configuration, enable sequential convolution instead of last layer
textureSize: 0, // Requested Texture size for the model, if unknown can be 0.
warning:
"This model may need dedicated graphics card. For more info please check with Browser Resources <i class='fa fa-cogs'></i>.", // Warning message to show when select the model.
inferenceDelay: 100, // Delay in ms time while looping layers applying.
description:
'Parcellation of the brain into 17 regions: gray and white matter plus subcortical areas. This is a robust model able to handle range of data quality, including varying saturation, and even clinical scans. It may work on infant brains, but your mileage may vary.'
},
{
id: 5,
type: 'Atlas',
path: './models/model30chan18cls/model.json',
modelName: '\u{1FA93} Subcortical + GWM (Low Mem, Slow)',
labelsPath: './models/model30chan18cls/labels.json',
colorsPath: './models/model30chan18cls/colorLUT.json',
colormapPath: './models/model30chan18cls/colormap.json',
preModelId: null, // Model run first e.g. crop the brain { null, 1, 2, .. }
preModelPostProcess: false, // If true, perform postprocessing to remove noisy regions after preModel inference generate output.
isBatchOverlapEnable: false, // create extra overlap batches for inference
numOverlapBatches: 200, // Number of extra overlap batches for inference
enableTranspose: true, // Keras and tfjs input orientation may need a tranposing step to be matched
enableCrop: true, // For speed-up inference, crop brain from background before feeding to inference model to lower memory use.
cropPadding: 0, // Padding size add to cropped brain
autoThreshold: 0.2, // Threshold between 0 and 1, given no preModel and tensor is normalized either min-max or by quantiles. Will remove noisy voxels around brain
enableQuantileNorm: false, // Some models needs Quantile Normaliztion.
filterOutWithPreMask: false, // Can be used to multiply final output with premodel output mask to crean noisy areas
enableSeqConv: true, // For low memory system and low configuration, enable sequential convolution instead of last layer
textureSize: 0, // Requested Texture size for the model, if unknown can be 0.
warning:
"This model may need dedicated graphics card. For more info please check with Browser Resources <i class='fa fa-cogs'></i>.", // Warning message to show when select the model.
inferenceDelay: 100, // Delay in ms time while looping layers applying.
description:
'Parcellation of the brain into 17 regions: gray and white matter plus subcortical areas. This is a robust model able to handle range of data quality, including varying saturation, and even clinical scans. It may work on infant brains, but your mileage may vary.'
},
{
id: 6,
type: 'Atlas',
path: './models/model18cls/model.json',
modelName: '\u{1FA93} Subcortical + GWM (Low Mem, Faster)',
labelsPath: './models/model18cls/labels.json',
colorsPath: './models/model18cls/colorLUT.json',
colormapPath: './models/model18cls/colormap.json',
preModelId: null, // model run first e.g. Brain_Extraction { null, 1, 2, .. }
preModelPostProcess: false, // If true, perform postprocessing to remove noisy regions after preModel inference generate output.
isBatchOverlapEnable: false, // create extra overlap batches for inference
numOverlapBatches: 200, // Number of extra overlap batches for inference
enableTranspose: true, // Keras and tfjs input orientation may need a tranposing step to be matched
enableCrop: true, // For speed-up inference, crop brain from background before feeding to inference model to lower memory use.
cropPadding: 0, // Padding size add to cropped brain
autoThreshold: 0.2, // Threshold between 0 and 1, given no preModel and tensor is normalized either min-max or by quantiles. Will remove noisy voxels around brain
enableQuantileNorm: false, // Some models needs Quantile Normaliztion.
filterOutWithPreMask: false, // Can be used to multiply final output with premodel output mask to crean noisy areas
enableSeqConv: true, // For low memory system and low configuration, enable sequential convolution instead of last layer
textureSize: 0, // Requested Texture size for the model, if unknown can be 0.
warning:
"This model may need dedicated graphics card. For more info please check with Browser Resources <i class='fa fa-cogs'></i>.", // Warning message to show when select the model.
inferenceDelay: 100, // Delay in ms time while looping layers applying.
description:
'Parcellation of the brain into 17 regions: gray and white matter plus subcortical areas. This is a robust model able to handle range of data quality, including varying saturation, and even clinical scans. It may work on infant brains, but your mileage may vary.'
},
{
id: 7,
type: 'Atlas',
path: './models/model30chan18cls/model.json',
modelName: '\u{1F52A}\u{1FA93} Subcortical + GWM (Failsafe, Less Acc)',
labelsPath: './models/model30chan18cls/labels.json',
colorsPath: './models/model30chan18cls/colorLUT.json',
colormapPath: './models/model30chan18cls/colormap.json',
preModelId: 1, // model run first e.g. Brain_Extraction { null, 1, 2, .. }
preModelPostProcess: false, // If true, perform postprocessing to remove noisy regions after preModel inference generate output.
isBatchOverlapEnable: false, // create extra overlap batches for inference
numOverlapBatches: 200, // Number of extra overlap batches for inference
enableTranspose: true, // Keras and tfjs input orientation may need a tranposing step to be matched
enableCrop: true, // For speed-up inference, crop brain from background before feeding to inference model to lower memory use.
cropPadding: 0, // Padding size add to cropped brain
autoThreshold: 0, // Threshold between 0 and 1, given no preModel and tensor is normalized either min-max or by quantiles. Will remove noisy voxels around brain
enableQuantileNorm: false, // Some models needs Quantile Normaliztion.
filterOutWithPreMask: false, // Can be used to multiply final output with premodel output mask to crean noisy areas
enableSeqConv: false, // For low memory system and low configuration, enable sequential convolution instead of last layer
textureSize: 0, // Requested Texture size for the model, if unknown can be 0.
warning:
"This model may need dedicated graphics card. For more info please check with Browser Resources <i class='fa fa-cogs'></i>.", // Warning message to show when select the model.
inferenceDelay: 100, // Delay in ms time while looping layers applying.
description:
'Parcellation of the brain into 17 regions: gray and white matter plus subcortical areas. This is not a robust model, it may work on low data quality, including varying saturation, and even clinical scans. It may work also on infant brains, but your mileage may vary.'
},
{
id: 8,
type: 'Atlas',
path: './models/model30chan50cls/model.json',
modelName: '\u{1F52A} Aparc+Aseg 50 (High Mem, Fast)',
labelsPath: './models/model30chan50cls/labels.json',
colorsPath: './models/model30chan50cls/colorLUT.json',
colormapPath: './models/model30chan50cls/colormap.json',
preModelId: 1, // Model run first e.g. crop the brain { null, 1, 2, .. }
preModelPostProcess: false, // If true, perform postprocessing to remove noisy regions after preModel inference generate output.
isBatchOverlapEnable: false, // create extra overlap batches for inference
numOverlapBatches: 200, // Number of extra overlap batches for inference
enableTranspose: true, // Keras and tfjs input orientation may need a tranposing step to be matched
enableCrop: true, // For speed-up inference, crop brain from background before feeding to inference model to lower memory use.
cropPadding: 0, // Padding size add to cropped brain
autoThreshold: 0, // Threshold between 0 and 1, given no preModel and tensor is normalized either min-max or by quantiles. Will remove noisy voxels around brain
enableQuantileNorm: true, // Some models needs Quantile Normaliztion.
filterOutWithPreMask: false, // Can be used to multiply final output with premodel output mask to crean noisy areas
enableSeqConv: false, // For low memory system and low configuration, enable sequential convolution instead of last layer
textureSize: 0, // Requested Texture size for the model, if unknown can be 0.
warning:
"This model may need dedicated graphics card. For more info please check with Browser Resources <i class='fa fa-cogs'></i>.", // Warning message to show when select the model.
inferenceDelay: 100, // Delay in ms time while looping layers applying.
description:
'This is a 50-class model, that segments the brain into the Aparc+Aseg Freesurfer Atlas but one where cortical homologues are merged into a single class.'
},
{
id: 9,
type: 'Atlas',
path: './models/model30chan50cls/model.json',
modelName: '\u{1F52A} Aparc+Aseg 50 (Low Mem, Slow)',
labelsPath: './models/model30chan50cls/labels.json',
colorsPath: './models/model30chan50cls/colorLUT.json',
colormapPath: './models/model30chan50cls/colormap.json',
preModelId: 1, // Model run first e.g. crop the brain { null, 1, 2, .. }
preModelPostProcess: false, // If true, perform postprocessing to remove noisy regions after preModel inference generate output.
isBatchOverlapEnable: false, // create extra overlap batches for inference
numOverlapBatches: 200, // Number of extra overlap batches for inference
enableTranspose: true, // Keras and tfjs input orientation may need a tranposing step to be matched
enableCrop: true, // For speed-up inference, crop brain from background before feeding to inference model to lower memory use.
cropPadding: 0, // Padding size add to cropped brain
autoThreshold: 0, // Threshold between 0 and 1, given no preModel and tensor is normalized either min-max or by quantiles. Will remove noisy voxels around brain
enableQuantileNorm: true, // Some models needs Quantile Normaliztion.
filterOutWithPreMask: false, // Can be used to multiply final output with premodel output mask to crean noisy areas
enableSeqConv: true, // For low memory system and low configuration, enable sequential convolution instead of last laye
textureSize: 0, // Requested Texture size for the model, if unknown can be 0.
warning:
"This model may need dedicated graphics card. For more info please check with Browser Resources <i class='fa fa-cogs'></i>.", // Warning message to show when select the model.
inferenceDelay: 100, // Delay in ms time while looping layers applying.
description:
'This is a 50-class model, that segments the brain into the Aparc+Aseg Freesurfer Atlas but one where cortical homologues are merged into a single class. The model use sequential convolution for inference to overcome browser memory limitations but leads to longer computation time.'
},
// './models/model5_gw_ae/colorLUT.json',
{
id: 10,
type: 'Brain_Extraction',
path: './models/model5_gw_ae/model.json',
modelName: '\u26A1 Extract the Brain (FAST)',
labelsPath: null,
colorsPath: null,
preModelId: null, // Model run first e.g. crop the brain { null, 1, 2, .. }
preModelPostProcess: false, // If true, perform postprocessing to remove noisy regions after preModel inference generate output.
isBatchOverlapEnable: false, // create extra overlap batches for inference
numOverlapBatches: 0, // Number of extra overlap batches for inference
enableTranspose: true, // Keras and tfjs input orientation may need a tranposing step to be matched
enableCrop: true, // For speed-up inference, crop brain from background before feeding to inference model to lower memory use.
cropPadding: 18, // Padding size add to cropped brain
autoThreshold: 0, // Threshold between 0 and 1, given no preModel and tensor is normalized either min-max or by quantiles. Will remove noisy voxels around brain
enableQuantileNorm: false, // Some models needs Quantile Normaliztion.
filterOutWithPreMask: false, // Can be used to multiply final output with premodel output mask to crean noisy areas
enableSeqConv: false, // For low memory system and low configuration, enable sequential convolution instead of last layer
textureSize: 0, // Requested Texture size for the model, if unknown can be 0.
warning: null, // Warning message to show when select the model.
inferenceDelay: 100, // Delay in ms time while looping layers applying.
description:
'Extract the brain fast model operates on full T1 image in a single pass, but uses only 5 filters per layer. Can work on integrated graphics cards but is barely large enough to provide good accuracy. Still more accurate than the failsafe version.'
},
{
id: 11,
type: 'Brain_Extraction',
path: './models/model11_gw_ae/model.json',
modelName: '\u{1F52A} Extract the Brain (High Acc, Slow)',
labelsPath: null,
colorsPath: null,
preModelId: null, // Model run first e.g. crop the brain { null, 1, 2, .. }
preModelPostProcess: false, // If true, perform postprocessing to remove noisy regions after preModel inference generate output.
isBatchOverlapEnable: false, // create extra overlap batches for inference
numOverlapBatches: 0, // Number of extra overlap batches for inference
enableTranspose: true, // Keras and tfjs input orientation may need a tranposing step to be matched
enableCrop: true, // For speed-up inference, crop brain from background before feeding to inference model to lower memory use.
cropPadding: 0, // Padding size add to cropped brain
autoThreshold: 0, // Threshold between 0 and 1, given no preModel and tensor is normalized either min-max or by quantiles. Will remove noisy voxels around brain
enableQuantileNorm: false, // Some models needs Quantile Normaliztion.
filterOutWithPreMask: false, // Can be used to multiply final output with premodel output mask to crean noisy areas
enableSeqConv: true, // For low memory system and low configuration, enable sequential convolution instead of last layer
textureSize: 0, // Requested Texture size for the model, if unknown can be 0.
warning:
"This model may need dedicated graphics card. For more info please check with Browser Resources <i class='fa fa-cogs'></i>.",
inferenceDelay: 100, // Delay in ms time while looping layers applying.
description:
'Extract the brain high accuracy model operates on full T1 image in a single pass, but uses only 11 filters per layer. Can work on dedicated graphics cards. Still more accurate than the fast version.'
},
{
id: 12,
type: 'Brain_Masking',
path: './models/model5_gw_ae/model.json',
modelName: '\u26A1 Brain Mask (FAST)',
labelsPath: null,
colorsPath: null,
colormapPath: './models/model5_gw_ae/colormap.json',
preModelId: null, // Model run first e.g. crop the brain { null, 1, 2, .. }
preModelPostProcess: false, // If true, perform postprocessing to remove noisy regions after preModel inference generate output.
isBatchOverlapEnable: false, // create extra overlap batches for inference
numOverlapBatches: 0, // Number of extra overlap batches for inference
enableTranspose: true, // Keras and tfjs input orientation may need a tranposing step to be matched
enableCrop: true, // For speed-up inference, crop brain from background before feeding to inference model to lower memory use.
cropPadding: 17, // Padding size add to cropped brain
autoThreshold: 0, // Threshold between 0 and 1, given no preModel and tensor is normalized either min-max or by quantiles. Will remove noisy voxels around brain
enableQuantileNorm: false, // Some models needs Quantile Normaliztion.
filterOutWithPreMask: false, // Can be used to multiply final output with premodel output mask to crean noisy areas
enableSeqConv: false, // For low memory system and low configuration, enable sequential convolution instead of last layer
textureSize: 0, // Requested Texture size for the model, if unknown can be 0.
warning: null, // Warning message to show when select the model.
inferenceDelay: 100, // Delay in ms time while looping layers applying.
description:
'This fast masking model operates on full T1 image in a single pass, but uses only 5 filters per layer. Can work on integrated graphics cards but is barely large enough to provide good accuracy. Still more accurate than failsafe version.'
},
{
id: 13,
type: 'Brain_Masking',
path: './models/model11_gw_ae/model.json',
modelName: '\u{1F52A} Brain Mask (High Acc, Low Mem)',
labelsPath: null,
colorsPath: null,
preModelId: null, // Model run first e.g. crop the brain { null, 1, 2, .. }
preModelPostProcess: false, // If true, perform postprocessing to remove noisy regions after preModel inference generate output.
isBatchOverlapEnable: false, // create extra overlap batches for inference
numOverlapBatches: 0, // Number of extra overlap batches for inference
enableTranspose: true, // Keras and tfjs input orientation may need a tranposing step to be matched
enableCrop: true, // For speed-up inference, crop brain from background before feeding to inference model to lower memory use.
cropPadding: 0, // Padding size add to cropped brain
autoThreshold: 0, // Threshold between 0 and 1, given no preModel and tensor is normalized either min-max or by quantiles. Will remove noisy voxels around brain
enableQuantileNorm: true, // Some models needs Quantile Normaliztion.
filterOutWithPreMask: false, // Can be used to multiply final output with premodel output mask to crean noisy areas
enableSeqConv: true, // For low memory system and low configuration, enable sequential convolution instead of last layer
textureSize: 0, // Requested Texture size for the model, if unknown can be 0.
warning:
"This model may need dedicated graphics card. For more info please check with Browser Resources <i class='fa fa-cogs'></i>.",
inferenceDelay: 100, // Delay in ms time while looping layers applying.
description:
'This masking model operates on full T1 image in a single pass, but uses 11 filters per layer. Can work on dedicated graphics cards. Still more accurate than fast version.'
},
{
id: 14,
type: 'Atlas',
path: './models/model21_104class/model.json',
modelName: '\u{1F52A} Aparc+Aseg 104 (High Mem, Fast)',
labelsPath: './models/model21_104class/labels.json',
colorsPath: './models/model21_104class/colorLUT.json',
colormapPath: './models/model21_104class/colormap.json',
preModelId: 1, // model run first e.g. Brain_Extraction { null, 1, 2, .. }
preModelPostProcess: false, // If true, perform postprocessing to remove noisy regions after preModel inference generate output.
isBatchOverlapEnable: false, // create extra overlap batches for inference
numOverlapBatches: 200, // Number of extra overlap batches for inference
enableTranspose: true, // Keras and tfjs input orientation may need a tranposing step to be matched
enableCrop: true, // For speed-up inference, crop brain from background before feeding to inference model to lower memory use.
cropPadding: 0, // Padding size add to cropped brain
autoThreshold: 0, // Threshold between 0 and 1, given no preModel and tensor is normalized either min-max or by quantiles. Will remove noisy voxels around brain
enableQuantileNorm: false, // Some models needs Quantile Normaliztion.
filterOutWithPreMask: false, // Can be used to multiply final output with premodel output mask to crean noisy areas
enableSeqConv: false, // For low memory system and low configuration, enable sequential convolution instead of last layer
textureSize: 0, // Requested Texture size for the model, if unknown can be 0.
warning:
"This model may need dedicated graphics card. For more info please check with Browser Resources <i class='fa fa-cogs'></i>.", // Warning message to show when select the model.
inferenceDelay: 100, // Delay in ms time while looping layers applying.
description:
'FreeSurfer aparc+aseg atlas 104 parcellate brain areas into 104 regions. It contains a combination of the Desikan-Killiany atlas for cortical area and also segmentation of subcortical regions.'
},
{
id: 15,
type: 'Atlas',
path: './models/model21_104class/model.json',
modelName: '\u{1F52A} Aparc+Aseg 104 (Low Mem, Slow)',
labelsPath: './models/model21_104class/labels.json',
colorsPath: './models/model21_104class/colorLUT.json',
colormapPath: './models/model21_104class/colormap.json',
preModelId: 1, // model run first e.g. Brain_Extraction { null, 1, 2, .. }
preModelPostProcess: false, // If true, perform postprocessing to remove noisy regions after preModel inference generate output.
isBatchOverlapEnable: false, // create extra overlap batches for inference
numOverlapBatches: 200, // Number of extra overlap batches for inference
enableTranspose: true, // Keras and tfjs input orientation may need a tranposing step to be matched
enableCrop: true, // For speed-up inference, crop brain from background before feeding to inference model to lower memory use.
cropPadding: 0, // Padding size add to cropped brain
autoThreshold: 0, // Threshold between 0 and 1, given no preModel and tensor is normalized either min-max or by quantiles. Will remove noisy voxels around brain
enableQuantileNorm: false, // Some models needs Quantile Normaliztion.
filterOutWithPreMask: false, // Can be used to multiply final output with premodel output mask to crean noisy areas
enableSeqConv: true, // For low memory system and low configuration, enable sequential convolution instead of last layer
textureSize: 0, // Requested Texture size for the model, if unknown can be 0.
warning:
"This model may need dedicated graphics card. For more info please check with Browser Resources <i class='fa fa-cogs'></i>.", // Warning message to show when select the model.
inferenceDelay: 100, // Delay in ms time while looping layers applying.
description:
'FreeSurfer aparc+aseg atlas 104 parcellate brain areas into 104 regions. It contains a combination of the Desikan-Killiany atlas for cortical area and also segmentation of subcortical regions. The model use sequential convolution for inference to overcome browser memory limitations but leads to longer computation time. '
}
] // inferenceModelsList
async function checkZero(timeValue) {
return timeValue < 10 ? timeValue : '0' + timeValue
}
async function detectBrowser() {
if (navigator.userAgent.indexOf('OPR/') > -1) {
return 'Opera'
} else if (navigator.userAgent.indexOf('Edg/') > -1) {
return 'Edge'
} else if (navigator.userAgent.indexOf('Falkon/') > -1) {
return 'Falkon'
} else if (navigator.userAgent.indexOf('Chrome/') > -1) {
return 'Chrome'
} else if (navigator.userAgent.indexOf('Firefox/') > -1) {
return 'Firefox'
} else if (navigator.userAgent.indexOf('Safari/') > -1) {
return 'Safari'
} else if (navigator.userAgent.indexOf('MSIE/') > -1 || navigator.userAgent.indexOf('rv:') > -1) {
return 'IExplorer'
} else {
return 'Unknown'
}
}
async function detectBrowserVersion() {
if (navigator.userAgent.indexOf('OPR/') > -1) {
return parseInt(navigator.userAgent.split('OPR/')[1])
} else if (navigator.userAgent.indexOf('Edg/') > -1) {
return parseInt(navigator.userAgent.split('Edg/')[1])
} else if (navigator.userAgent.indexOf('Falkon/') > -1) {
return parseInt(navigator.userAgent.split('Falkon/')[1])
} else if (navigator.userAgent.indexOf('Chrome/') > -1) {
return parseInt(navigator.userAgent.split('Chrome/')[1])
} else if (navigator.userAgent.indexOf('Firefox/') > -1) {
return parseInt(navigator.userAgent.split('Firefox/')[1])
} else if (navigator.userAgent.indexOf('Safari/') > -1) {
return parseInt(navigator.userAgent.split('Safari/')[1])
} else if (navigator.userAgent.indexOf('MSIE/') > -1 || navigator.userAgent.indexOf('rv:') > -1) {
return parseInt(navigator.userAgent.split('MSIE/')[1])
} else {
return Infinity
}
}
async function detectOperatingSys() {
if (navigator.userAgent.indexOf('Win') > -1) {
return 'Windows'
} else if (navigator.userAgent.indexOf('Mac') > -1) {
return 'MacOS'
} else if (navigator.userAgent.indexOf('Linux') > -1) {
return 'Linux'
} else if (navigator.userAgent.indexOf('UNIX') > -1) {
return 'UNIX'
} else {
return 'Unknown'
}
}
async function checkWebGl2(callbackUI) {
const gl = document.createElement('canvas').getContext('webgl2')
if (!gl) {
if (typeof WebGL2RenderingContext !== 'undefined') {
const msg = 'WebGL2 may be disabled. Please try updating video card drivers'
callbackUI(msg, -1, msg)
} else {
console.log('WebGL2 is not supported')
}
return false
} else {
console.log('WebGl2 is enabled')
return true
}
}
async function detectGPUVendor() {
const gl = document.createElement('canvas').getContext('webgl')
let debugInfo
if (gl) {
debugInfo = gl.getExtension('WEBGL_debug_renderer_info')
if (debugInfo) {
const result = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL)
// --e.g. : NVIDIA Corporation
if (result.indexOf('(') > -1 && result.indexOf(')') > -1) {
return result.substring(result.indexOf('(') + 1, result.indexOf(')'))
}
return result
}
}
return null
}
async function detectGPUVendor_v0() {
const gl = document.createElement('canvas').getContext('webgl')
if (gl) {
const debugInfo = gl.getExtension('WEBGL_debug_renderer_info')
return debugInfo ? gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL) : null
} else {
return null
}
}
async function detectGPUCardType_v0() {
const gl = document.createElement('canvas').getContext('webgl')
if (gl) {
if (detectBrowser() === 'Firefox') {
// -- return e.g: "GeForce GTX 980/PCIe/SSE2"
return gl.getParameter(gl.RENDERER)
}
const debugInfo = gl.getExtension('WEBGL_debug_renderer_info')
return debugInfo ? gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) : null
} else {
return null
}
}
async function detectGPUCardType() {
const gl = document.createElement('canvas').getContext('webgl')
let debugInfo
if (gl) {
if (detectBrowser() === 'Firefox') {
// -- return e.g: "GeForce GTX 980/PCIe/SSE2"
return gl.getParameter(gl.RENDERER)
}
debugInfo = gl.getExtension('WEBGL_debug_renderer_info')
if (debugInfo) {
let result = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL)
// --e.g. : ANGLE (NVIDIA Corporation, GeForce GTX 1050 Ti/PCIe/SSE2, OpenGL 4.5.0 NVIDIA 390.144) as with Chrome
// Or: GeForce GTX 1050 Ti/PCIe/SSE2 as with fireFox
if (result.indexOf('(') > -1 && result.indexOf(')') > -1 && result.indexOf('(R)') === -1) {
result = result.substring(result.indexOf('(') + 1, result.indexOf(')'))
if (result.split(',').length === 3) {
return result.split(',')[1].trim()
}
}
return result
}
}
return null
}
async function getCPUNumCores() {
return navigator.hardwareConcurrency
}
async function isChrome() {
return /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor)
}
async function submitTiming2GoogleSheet(dataObj, callbackUI) {
if (navigator.onLine) {
const msg = 'Telemetry not yet supported'
callbackUI(msg, -1, msg)
console.log(dataObj)
/*
// -- Fill form with data to submit
Object.keys(dataObj).forEach(dataKey =>{
document.getElementById(dataKey).value = dataObj[dataKey];
})
//-- Settings of submission
const scriptURL = 'https://script.google.com/macros/s/AKfycbwn-Ix6IVGOwUSU1VBU8hFcABT9PqwCwN90UxfK_fXp5CEfxvIoQHZXs2XQRZQo_N8I/exec'
const form = document.forms['google-sheet']
//-- Add event handler to the form.
form.addEventListener('submit', e => {
e.preventDefault()
fetch(scriptURL, { method: 'POST', body: new FormData(form)})
.then(response => console.log("------Done------"))
.catch(error => console.error('Error!', error.message))
})
//-- Submit the form
document.getElementById("SubmitStatisticalData").click();
*/
} else {
console.log(' Offline Mode ')
}
}
async function getModelNumParameters(modelObj) {
let numParameters = 0
for (let layerIdx = 0; layerIdx < modelObj.layers.length; layerIdx++) {
numParameters += modelObj.layers[layerIdx].countParams()
}
return numParameters
}
async function getModelNumLayers(modelObj) {
return modelObj.layers.length
}
async function isModelChnlLast(modelObj) {
for (let layerIdx = 0; layerIdx < modelObj.layers.length; layerIdx++) {
if (modelObj.layersByDepth[layerIdx][0].dataFormat) {
return modelObj.layersByDepth[layerIdx][0].dataFormat === 'channelsLast'
}
}
}
async function load_model(modelUrl) {
return await tf.loadLayersModel(modelUrl)
}
async function getAllSlices2D(allSlices, slice_height, slice_width) {
const allSlices_2D = []
for (let sliceIdx = 0; sliceIdx < allSlices.length; sliceIdx++) {
allSlices_2D.push(tf.tensor(allSlices[sliceIdx], [slice_height, slice_width]))
}
return allSlices_2D
}
async function getSlices3D(allSlices_2D) {
return tf.stack(allSlices_2D)
}
async function getAllSlicesData1D(num_of_slices, niftiHeader, niftiImage) {
// Get nifti dimensions
const cols = niftiHeader.dims[1] // Slice width
const rows = niftiHeader.dims[2] // Slice height
let typedData
if (niftiHeader.datatypeCode === 2) {
// enum from nvimage/utils DT_UINT8 = 2
typedData = new Uint8Array(niftiImage)
} else if (niftiHeader.datatypeCode === 4) {
// DT_INT16 = 4
typedData = new Int16Array(niftiImage)
} else if (niftiHeader.datatypeCode === 8) {
// DT_INT32 = 8
typedData = new Int32Array(niftiImage)
} else if (niftiHeader.datatypeCode === 16) {
// DT_FLOAT32 = 16
typedData = new Float32Array(niftiImage)
} else if (niftiHeader.datatypeCode === 64) {
// DT_FLOAT64 = 64
typedData = new Float64Array(niftiImage)
} else if (niftiHeader.datatypeCode === 256) {
// DT_INT8 = 256
typedData = new Int8Array(niftiImage)
} else if (niftiHeader.datatypeCode === 512) {
// DT_UINT16 = 512
typedData = new Uint16Array(niftiImage)
} else if (niftiHeader.datatypeCode === 768) {
// DT_UINT32 = 768
typedData = new Uint32Array(niftiImage)
} else {
return
}
const allSlices = []
let offset3D = 0
// Draw pixels
for (let slice = 0; slice < num_of_slices; slice++) {
const slice = new Array(rows * cols)
let offset2D = 0
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
const value = typedData[offset3D++]
// Create 1Dim Array of pixel value, this 1 dim represents one channel
slice[offset2D++] = value & 0xff
}
}
allSlices.push(slice)
}
return allSlices
}
async function calculateQuantiles(tensor, lowerQuantile = 0.01, upperQuantile = 0.99) {
// Flatten the tensor
const flatTensor = tensor.flatten()
// Convert the flattened tensor to an array to sort it
const flatArray = await flatTensor.array()
flatArray.sort((a, b) => a - b) // Sort the array in ascending order
// Convert the sorted array back to a tensor
const sortedTensor = tf.tensor1d(flatArray)
// Calculate the indices for the quantiles
const numElements = sortedTensor.shape[0]
const lowIndex = Math.floor(numElements * lowerQuantile)
const highIndex = Math.ceil(numElements * upperQuantile) - 1 // Subtract 1 because indices are 0-based
// Slice the sorted tensor to get qmin and qmax
const qmin = sortedTensor.slice(lowIndex, 1) // Get the value at the low index
const qmax = sortedTensor.slice(highIndex, 1) // Get the value at the high index
// Get the actual values from the tensors
const qminValue = (await qmin.array())[0]
const qmaxValue = (await qmax.array())[0]
// Clean up tensors to free memory
flatTensor.dispose()
sortedTensor.dispose()
qmin.dispose()
qmax.dispose()
return { qmin: qminValue, qmax: qmaxValue }
}
async function quantileNormalizeVolumeData(tensor, lowerQuantile = 0.05, upperQuantile = 0.95) {
// Call calculateQuantiles and wait for the result
const { qmin, qmax } = await calculateQuantiles(tensor, lowerQuantile, upperQuantile)
// Convert qmin and qmax back to scalars
const qminScalar = tf.scalar(qmin)
const qmaxScalar = tf.scalar(qmax)
// Perform the operation: (tensor - qmin) / (qmax - qmin)
const resultTensor = tensor.sub(qminScalar).div(qmaxScalar.sub(qminScalar))
// Dispose of the created scalars to free memory
qminScalar.dispose()
qmaxScalar.dispose()
// Return the resulting tensor
return resultTensor
}
async function minMaxNormalizeVolumeData(volumeData) {
// Normalize the data to the range 0 - 1 using min-max scaling
const volumeData_Max = volumeData.max()
const volumeData_Min = volumeData.min()
const normalizedSlices_3d = await volumeData.sub(volumeData_Min).div(volumeData_Max.sub(volumeData_Min))
return normalizedSlices_3d
}
async function inferenceFullVolumeSeqCovLayer(
model,
slices_3d,
input_shape,
isChannelLast,
num_of_slices,
slice_height,
slice_width
) {
window.alert('inferenceFullVolumeSeqCovLayer() is not dead code?')
}
async function inferenceFullVolume(
model,
slices_3d,
input_shape,
isChannelLast,
num_of_slices,
slice_height,
slice_width
) {
window.alert('inferenceFullVolume() is not dead code?')
}
async function inferenceSubVolumes(model, slices_3d, num_of_slices, slice_height, slice_width, pipeline1_out = null) {
window.alert('inferenceSubVolumes() is not dead code?')
}
async function tensor2LightBuffer(tensor, dtype) {
window.alert('tensor2LightBuffer() is not dead code?')
// return new Buffer(tensor.shape, dtype, Array.from(tensor.dataSync()) );
}
async function draw3dObjBoundingVolume(unstackOutVolumeTensor) {
window.alert('draw3dObjBoundingVolume() is not dead code?')
/*
console.log("Plot cropped volume shape ... ");
// Convert all slices into 1 Dim array to download
let allOutputSlices3DCC = [];
let allOutputSlices3DContours = [];
// dataSync() using to flatten array. Takes around 1.5 s
for(let sliceTensorIdx = 0; sliceTensorIdx < unstackOutVolumeTensor.length; sliceTensorIdx++ ) {
allOutputSlices3DCC[sliceTensorIdx] = Array.from(unstackOutVolumeTensor[sliceTensorIdx].dataSync());
}
// if(false) { // Enable contour for overlay option
// // Remove noisy regions using 3d CC
// let sliceWidth = niftiHeader.dims[1];
// let sliceHeight = niftiHeader.dims[2];
// allOutputSlices3DCC = findVolumeContours(allOutputSlices3DCC, sliceHeight, sliceWidth, 2 );
// }
let allOutputSlices3DCC1DimArray = [];
// Use this conversion to download output slices as nii file. Takes around 0.5 s
for(let sliceIdx = 0; sliceIdx < allOutputSlices3DCC.length; sliceIdx++ ) {
allOutputSlices3DCC1DimArray.push.apply(allOutputSlices3DCC1DimArray, allOutputSlices3DCC[sliceIdx]);
}
console.log("Done with allOutputSlices3DCC1DimArray ")
let brainOut = [];
let brainMaskTensor1d = binarizeVolumeDataTensor(tf.tensor1d(allOutputSlices3DCC1DimArray));
brainOut = Array.from(brainMaskTensor1d.dataSync());
// labelArrayBuffer = createNiftiOutArrayBuffer(rawNiftiData, brainExtractionData1DimArr);
let labelArrayBuffer = createNiftiOutArrayBuffer(rawNiftiData, brainOut);
TODO Papaa specific code?
if(true) { // flag to not draw for now
if(opts.isColorEnable) {
let blob = new Blob([labelArrayBuffer], {type: "application/octet-binary;charset=utf-8"});
let file = new File([blob], "temp.nii");
params_label["files"] = [file];
params_label[file["name"]] = {lut: "Grayscale", interpolation: false};
} else {
params_label["binaryImages"] = [labelArrayBuffer];
}
// Set the view of container-2 as container-1
params_label["mainView"] = papayaContainers[0].viewer.mainImage.sliceDirection == 1? "axial" :
papayaContainers[0].viewer.mainImage.sliceDirection == 2? "coronal" : "sagittal";
papaya.Container.resetViewer(1, params_label);
papayaContainers[1].viewer.screenVolumes[0].alpha = 0.2; // 0 to 1 screenVolumes[0] is first image loaded in Labels viewer
papayaContainers[1].viewer.drawViewer(true, false);
// To sync swap view button
document.getElementById(PAPAYA_CONTROL_MAIN_SWAP_BUTTON_CSS + papayaContainers[0].containerIndex).addEventListener("click", function(){
papayaContainers[1].viewer.rotateViews()
})
document.getElementById(PAPAYA_CONTROL_MAIN_SWAP_BUTTON_CSS + papayaContainers[1].containerIndex).addEventListener("click", function(){
papayaContainers[0].viewer.rotateViews()
})
}
*/
}
async function argMaxLarge(outVolumeBuffer, num_of_slices, slice_height, slice_width, numOfClasses, dtype = 'float32') {
window.alert('argMaxLarge() is not dead code?')
/*
if( findMinNumOfArrBufs(num_of_slices, slice_height, slice_width, numOfClasses, dtype) == 1) {
// console.log("Convert output tensor to buffer");
// reshape modelOutTensor.shape : [ 1, 256, 256, 256, 3 ] to [ 256, 256, 256, 3 ]
//-- let outVolumeBuffer = tensor2Buffer(modelOutTensor.relu().reshape([num_of_slices, slice_height, slice_width, numOfClasses]));
//-- let outVolumeBuffer = tensor2Buffer(modelOutTensor.reshape([num_of_slices, slice_height, slice_width, numOfClasses]));
//-- let outVolumeBuffer = tensor2LightBuffer(modelOutTensor.reshape([num_of_slices, slice_height, slice_width, numOfClasses]), dtype);
console.log("Start argMaxLarge for buffer with last axis -1")
let outBuffer = tf.buffer([num_of_slices, slice_height, slice_width ], dtype=tf.float32);
for(let depthIdx = 0; depthIdx < num_of_slices; depthIdx += 1) {
for(let rowIdx = 0; rowIdx < slice_height; rowIdx += 1) {
for(let colIdx = 0; colIdx < slice_width; colIdx += 1) {
// index of buffer with max Freq or max number so the index of that buffer is the right concensus label
let indexOfMaxVotedBuffer = -1;
// let maxVoxelValue = -Infinity;
let maxVoxelValue = -1000000;
for(let bufferIdx = 0; bufferIdx < numOfClasses; bufferIdx += 1) {
//Requested out of range element at 1,0,0,0. Buffer shape=1,256,256,256,3
let voxelValue = outVolumeBuffer.get(depthIdx, rowIdx, colIdx, bufferIdx );
if(maxVoxelValue <= voxelValue) {
maxVoxelValue = voxelValue;
indexOfMaxVotedBuffer = bufferIdx;
}
}
outBuffer.set(indexOfMaxVotedBuffer, depthIdx, rowIdx, colIdx);
}
}
}
console.log("argMaxLarge for buffer ..Done");
return outBuffer.toTensor();
} else {
console.log(" Terminated due to browser memory limitation (TODO: callbackUI)");
console.log("argMaxLarge needs buffer division .. ");
return 0;
}
*/
}
async function addZeroPaddingTo3dTensor(tensor3d, rowPadArr = [1, 1], colPadArr = [1, 1], depthPadArr = [1, 1]) {
if (tensor3d.rank !== 3) {
throw new Error('Tensor must be 3D')
}
return tensor3d.pad([rowPadArr, colPadArr, depthPadArr])
}
async function removeZeroPaddingFrom3dTensor(tensor3d, rowPad = 1, colPad = 1, depthPad = 1) {
if (tensor3d.rank !== 3) {
throw new Error('Tensor must be 3D')
}
let h, w, d
;[h, w, d] = tensor3d.shape
return tensor3d.slice([rowPad, colPad, depthPad], [h - 2 * rowPad, w - 2 * colPad, d - 2 * depthPad])
}
async function resizeWithZeroPadding(croppedTensor3d, newDepth, newHeight, newWidth, refVoxel, boundVolSizeArr) {
const row_pad_befor = refVoxel[0]
const col_pad_befor = refVoxel[1]
const depth_pad_befor = refVoxel[2]
// last and lower volume voxel
const row_max = row_pad_befor + boundVolSizeArr[0] - 1 // size [2, 2, 2] means 2 voxels total in each dim
const col_max = col_pad_befor + boundVolSizeArr[1] - 1
const depth_max = depth_pad_befor + boundVolSizeArr[2] - 1
const row_pad_after = newHeight - row_max - 1 > 0 ? newHeight - row_max - 1 : 0
const col_pad_after = newWidth - col_max - 1 > 0 ? newWidth - col_max - 1 : 0
const depth_pad_after = newDepth - depth_max - 1 > 0 ? newDepth - depth_max - 1 : 0
return croppedTensor3d.pad([
[row_pad_befor, row_pad_after],
[col_pad_befor, col_pad_after],
[depth_pad_befor, depth_pad_after]
])
}
async function applyMriThreshold(tensor, percentage) {
// Perform asynchronous operations outside of tf.tidy
const maxTensor = tensor.max()
const thresholdTensor = maxTensor.mul(percentage)
const threshold = await thresholdTensor.data() // Extracts the threshold value
// Dispose tensors not needed anymore
maxTensor.dispose()
thresholdTensor.dispose()
// Use tf.tidy for synchronous operations
return tf.tidy(() => {
const dataForProcessing = tensor.clone()
// Thresholding (assuming background has very low values compared to the head)
const mask = dataForProcessing.greater(threshold[0])
// -- const denoisedMriData = dataForProcessing.mul(mask);
// No need to manually dispose dataForProcessing and mask, as tf.tidy() will dispose them auto.
return mask
})
// -- return denoisedMriData;
}
async function binarizeVolumeDataTensor(volumeDataTensor) {
const alpha = 0
// element-wise: (x > 0 ? 1 : alpha * x ); e.g. Tenosr [0, 0.9, 0.8, -3] => Tensor [0, 1, 1, 0]
return volumeDataTensor.step(alpha)
}
async function generateBrainMask(
unstackOutVolumeTensor,
num_of_slices,
slice_height,
slice_width,
modelEntry,
opts,
callbackUI,
callbackImg,
isFinalImage = true
) {
console.log('Generate Brain Masking ... ')
// Convert all slices into 1 Dim array to download
let allOutputSlices3DCC = []
// const allOutputSlices3DContours = []
// dataSync() using to flatten array. Takes around 1.5 s
for (let sliceTensorIdx = 0; sliceTensorIdx < unstackOutVolumeTensor.length; sliceTensorIdx++) {
allOutputSlices3DCC[sliceTensorIdx] = Array.from(unstackOutVolumeTensor[sliceTensorIdx].dataSync())
}
const isPreModelPostProcessEnable = modelEntry.preModelPostProcess
// let isPreModelPostProcessEnable = inferenceModelsList[$$("selectModel").getValue() - 1]["preModelPostProcess"];
if (isPreModelPostProcessEnable) {
console.log('Phase-1 Post processing enabled ... ')
allOutputSlices3DCC = tf.tidy(() => {
// Remove noisy regions using 3d CC
// const sliceWidth = niftiHeader.dims[1]