-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLibrary.txt
973 lines (864 loc) · 32.1 KB
/
Library.txt
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
/* Copyright 2021 Regents of the University of Colorado
*
* 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 3 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 <https://www.gnu.org/licenses/>.
*
* Author: Christian Rickert <christian.rickert@cuanschutz.edu>
* Group: Human Immune Monitoring Shared Resource (HIMSR)
* University of Colorado, Anschutz Medical Campus
*
* Title: CU-MacroLibrary
* Summary: ImageJ2 macro library with variables and functions
*
* DOI: https://doi.org/10.5281/zenodo.4885048
* URL: https://github.com/christianrickert/CU-MacroLibrary/
*
* Description:
*
* CU-MacroLibrary uses the Fiji image processing package exclusively – there is no need
* to install additional plugins: You can simply edit or run this code by loading and
* executing it with the Macro plugin.
* To install the CU-MacroLibrary with your copy of Fiji, simply copy the "Library.txt"
* to "Fiji.app\macros\" and its content will be available to any executed or installed macro.
* In addition, ImageJ2's macro editor will autocomplete function names from the library.
*/
requires("1.53h"); // minimum ImageJ version
/*
* Variables
*/
// global, preset for all macros
var delimiter = ":";
var libraryVersion = "CU-MacroLibrary v1.00 (2023-04-28)";
/*
* Start
*/
print(libraryVersion);
/*
* Functions
*/
// Function to remove all selections
function clearAllSelections()
{
roiManager("deselect");
run("Select None");
}
// Function to color a selection group
function colorGroup(index, red, green, blue)
{
setForegroundColor(red, green, blue);
RoiManager.selectGroup(index);
if ( RoiManager.selected() > 0 )
roiManager("fill");
clearAllSelections();
}
// Function to remove all regions of interest
function deleteAllRegions()
{
if ( roiManager("count") > 0 )
{
clearAllSelections();
roiManager("delete");
}
}
// Function to remove all regions of interest from a specific group
function deleteGroupRegions(group)
{
RoiManager.selectGroup(group);
if ( RoiManager.selected() > 0 )
roiManager("delete");
clearAllSelections();
}
// Function to test if a string ends with suffixes from a list
function endsWithEither(string, suffixes)
{
suffixesLength = suffixes.length;
found = false;
for ( i = 0; i < suffixesLength; ++i )
{
if ( endsWith(string, suffixes[i]) )
found = true;
}
return found;
}
// Function extends and returns an array with default values
function extendArray(array, size, value)
{
while ( array.length < size )
{
array = Array.concat(array, value);
}
return array;
}
// Function to trigger the Java Virtual Machine garbage collection
function freeMemory()
{
call("java.lang.System.gc");
}
// Function to fill a region's pixels with a given gray value
function fillRegion(v)
{
Roi.getContainedPoints(xx, yy);
pixels = xx.length;
for ( i = 0; i < pixels; ++i )
setPixel(xx[i], yy[i], v);
}
// Function to put a window with a specific title into focus
function focusWindow(title)
{
previous = getTitle();
images = getList("image.titles");
imagesLength = images.length;
for ( i = 0; i < imagesLength; ++i )
{
selectWindow(images[i]);
if ( startsWith(getTitle(), title) ) // focus on requested or last window
break;
}
if ( !startsWith(getTitle(), title) ) // loop finished, let's check the result
selectWindow(previous);
}
// Function to retrieve all files with a given suffix from a folder (batch)
function getFilesInFolder(dialog, suffixes)
{
output = newArray();
filePath = File.openDialog(dialog);
parentFolder = File.getParent(filePath);
objects = getFileList(parentFolder); // files and folders
objectsLength = objects.length;
output = Array.concat(output, filePath); // selected file in folder
for ( i = 0; i < objectsLength; ++i ) // all other files in folder
{
objectPath = parentFolder + File.separator + objects[i];
if( endsWithEither(objectPath, suffixes) && objectPath != filePath )
output = Array.concat(output, objectPath);
}
return output;
}
// Function to return the index of the last ROI Manager element
function getLastRegionIndex()
{
return roiManager("count") - 1;
}
// Function to calculate the Median pixel value
function getMedian(min_in, max_in)
{
min_out = min_in;
max_out = max_in;
updateDisplayRange(NaN, NaN); // force pixel values update
if ( isNaN(min_in) || isNaN(max_in) )
{
getRawStatistics(nPixels, mean, min, max); // slice, not stack
if ( isNaN(min_in) )
min_out = min;
if ( isNaN(max_in) )
max_out = max;
}
setThreshold(min_out, max_out);
output = getValue("Median raw limit");
resetThreshold();
return output;
}
// Function to return the median value of an array
function getMedianValue(array, includeZeros) {
output = NaN;
if ( !includeZeros ) {
array = Array.deleteValue(array, 0.0);
}
arrayLength = array.length;
Array.sort(array); // in-place
if ( arrayLength > 0 ) {
if ( arrayLength == 1 ) { // single element (float or string)
output = parseFloat(array[0]);
} else if ( arrayLength % 2 != 0 ) { // odd number of elements
output = array[Math.floor(arrayLength / 2)];
} else { // even number of elements
rightIndex = Math.floor(arrayLength / 2);
leftIndex = rightIndex - 1;
output = (array[leftIndex] + array[rightIndex]) / 2.0;
}
}
return output;
}
// Function to get pixel calibration information
function getPixelCalibration()
{
output = newArray("unit", "unitsPerPixelWidth", "unitsPerPixelHeight", "pixelDimension");
getPixelSize(output[0], output[1], output[2], output[3]);
return output;
}
// Function to get id from region of interest name
function getRegionID(index)
{
regionName = getRegionName(index);
delimiterIndex = indexOf(regionName, delimiter);
regionID = substring(regionName, 0, delimiterIndex); // region id (without delimiter)
return regionID;
}
// Function to get label from region of interest name
function getRegionLabel(index)
{
regionName = getRegionName(index);
delimiterIndex = indexOf(regionName, delimiter);
regionLabel = substring(regionName, delimiterIndex + 1); // region label (without delimiter)
return regionLabel;
}
function getRegionName(index)
{
roiManager("select", index);
regionName = Roi.getName();
return regionName;
}
// Function to return relative overlap between two regions of interest
function getRegionOverlap(parentRegionIndex, childRegionIndex)
{
overlap = 0; // track overlap of child region with parent region
roiManager("select", childRegionIndex);
Roi.getContainedPoints(ch_xx, ch_yy); // pixels inside child region
ch_xx_length = ch_xx.length;
roiManager("select", parentRegionIndex);
for ( p = 0; p < ch_xx_length; ++p ) // iterate through child pixels
{
if ( Roi.contains(ch_xx[p], ch_yy[p]) ) // child pixel inside parent region
overlap++;
}
overlap = overlap / ch_xx_length * 100.0; // percentage
return overlap;
}
// Function to grow or shrink the current selection
function getResizedSelection(index, value, unit)
{
if ( unit == "pixel" )
pixel = " " + pixel;
else
pixel = "";
roiManager("select", index);
run("Enlarge...", "enlarge=" + v2p(value) + pixel); // always returns a selection
}
// Function to convert grayscale image masks into ROIs
function getRoisFromMasks(label, normalmode)
{
// Our basic assumption is that the background has a grayscale value of zero and that
// masks have sequentially incrementing values up to the total number of ROIs.
// The normal mode uses thresholding and the 'Create Selection' function, which detects
// disconnected regions independent of pixel distribution across the source image.
// The fast mode uses the 'doWand' function and might fail for some "objects, especially
// one pixel wide lines [...] unless they have been thresholded". However, disconnected
// clusters or pixels with the same gray value will never be connected to existing regions.
// We therefore introduce a merging step after the fast mode detection to overcome the
// detection limitations as much as possible.
// Notice that the fast mode detects significantly faster than the normal mode for large,
// connected regions (i.e. nuclei, cell matrix, cells, etc.) with only few isolated pixels.
// In contrast, the normal mode exhibits a fixed detection rate irrespective of the regions.
// It is therefore particularly suitable for cytoplasm or cell membrane region detection.
// Note: the ROI Manager has to be started before calling this function!
roiManager("UseNames", "true"); // enable full labels
output = 0; // ROI count
start = roiManager("count"); // start index at end of existing list
roi = 0; // ROI ID of current region
// convert image to 32-bit grayscale and get statistics
clearAllSelections(); // get full image for duplication
run("Duplicate...", "title=tmp"); // slice from stack
bits = bitDepth();
if ( bits != 32 && ( bits == 8 || bits == 16 ) ) // available type conversions
run("32-bit");
showStatus("!"); // suppress automatic status updates
// get regions of interest from grayscale values
getRawStatistics(pixels, mean, min, max);
if ( max > 0 )
{
if ( normalmode ) // normal mode for disconnected regions
{
if ( min == 0 ) // exclude background
min++;
for ( roi = min; roi <= max; ++roi )
{
setThreshold(roi, roi); // threshold individual mask by grayscale value
run("Create Selection"); // create selection from all masks, slow
if ( selectionType != -1 ) // selection with current threshold available
{
roiManager("add");
index = getLastRegionIndex();
renameRegion(index, toString(roi) + delimiter + label);
if ( roi % 20 == 0 || roi == max )
showStatus("!Adding " + roi + " out of " + max + " regions to ROI Manager...");
}
}
}
else // fast mode for connected regions
{
Color.setForegroundValue(0); // black, used by 'floodFill' function
getDimensions(width, height, channels, slices, frames);
group = 0; // ROI ID of current group
marker = "00000"; // temporary ROI ID, moved to top of ROI Manager list after sorting
value = 0; // gray value of current pixel
for ( x = 0; x < width; ++x )
{
for ( y = 0; y < height; ++y )
{
roi = getPixel(x, y);
if ( roi > 0 ) // region of interest mask
{
doWand(x, y, 0, "4-connected"); // create selection from single mask, fast
roiManager("add");
index = getLastRegionIndex();
renameRegion(index, marker + delimiter + roi);// adding temporary marker and region ID
floodFill(x, y); // exclude selected pixels from future search
count = (index - start) + 1;
if ( count % 1000 == 0 || count == max )
showStatus("!Adding " + count + " out of " + max + " regions to ROI Manager...");
}
}
}
stop = roiManager("count"); // stop index at end of updated list
roiManager("sort"); // move temporary ROIs to top of ROI Manager list
// merge ROI groups excluding the last one
rois = stop - start; // number of additional rois before merge
if ( rois > 1 )
{
group = getRegionLabel(0); // region ID of merge group
groupArray = newArray(0); // list of indices for merge group
roi = 0; // current region ID
// iterate ROI Manager list, merge all groups except for the last one
for ( index = 0; index < rois; ++index )
{
roi = getRegionLabel(index); // in this case: the region ID
if ( roi == group )
groupArray = Array.concat(groupArray, index); // add next item to group
else // roi != group
{
if ( groupArray.length == 1 ) // already connected region, update existing entry only
renameRegion((index - 1), toString(group) + delimiter + label); // rename merged region
else // multiple regionsa
{
if ( mergeRegions(groupArray) ) // add merged gregion to last index
{
RoiManager.setGroup(9); // mark disconnected regions for removal
renameRegion(getLastRegionIndex(), toString(group) + delimiter + label);
}
}
group = roi; // prepare next group
groupArray = newArray(toString(index));
}
count = (index - start) + 1;
if ( count % 1000 == 0 )
showStatus("!Merging " + count + " out of " + rois + " regions in ROI Manager...");
}
// merge the last group in the ROI Manager list, ignore merge status
if ( mergeRegions(groupArray) )
{
RoiManager.setGroup(9);
renameRegion(getLastRegionIndex(), toString(group) + delimiter + label);
}
RoiManager.selectGroup(9);
showStatus("!Deleting " + RoiManager.selected + " out of " + rois + " regions from ROI Manager...");
deleteGroupRegions(9); // remove temporary (disconnected) ROI IDs
roiManager("sort");
}
else // rois == 1
renameRegion(0, toString(1) + delimiter + "roi");
}
close("tmp");
showStatus(""); // enable status updates
roiManager("sort");
output = roiManager("count") - start;
}
return output
}
// Function to return an array of slice numbers for selected channel names
function getSlicesFromLabels(labels, channels)
{
// We can match partial patterns, i.e. "CD3" would match "CD3" and "CD31", but also "ABCD32".
// In order to avoid accidental multiple hits, one could either provide the full, unambigous
// slice label or make use of delimiting characters:
// "CD3 ", with a trailing space, would match "CD3 (Opal 540), but not "CD31 (Opal 620).
output = newArray(0);
channelsLength = channels.length;
labelsLength = labels.length;
label = "";
for ( i = 1; i <= labelsLength; ++i ) // iterate through slice labels
{
label = toLowerCase(labels[i - 1]);
for ( j = 0; j < channelsLength; ++j ) // iterate through selected channels
{
if ( label.contains(toLowerCase(channels[j])) )
output = Array.concat(output, i);
}
}
return output;
}
// Function initializes and returns an array with default values
function initializeArray(counts, value)
{
return Array.fill(newArray(counts), value);
}
// Function to initialize a new batch run
function initializeRun(version)
{
print("\\Clear"); // clear Log window
printDateTimeStamp();
print("ImageJ2 v" + IJ.getFullVersion);
print(version);
run("Close All"); // close all image windows
deleteAllRegions(); // remove all regions from ROI Manager
run("Clear Results"); // empty Results table
}
// Function to check, if a specific window is available
function isAvailableWindow(title)
{
output = false;
titles = getList("window.titles");
titleLength = titles.length;
for ( i = 0; i < titleLength; ++i )
{
if ( titles[i] == title )
output = true;
}
return output;
}
// Function to check if an element can be found in an array
function isInArray(array, element)
{
// The equality comparison treats integers and integer-strings interchangeably.
inArray = false;
arrayLength = array.length;
for ( i = 0; ( !inArray ) && ( i < arrayLength ); ++i )
{
if ( element == array[i] )
inArray = true;
}
return inArray;
}
// Function to check for approximate overlap between two regions of interest
function isInBounds(parentRegionIndex, childRegionIndex)
{
inBounds = false;
roiManager("select", childRegionIndex);
Roi.getBounds(ch_x, ch_y, ch_width, ch_height);
roiManager("select", parentRegionIndex);
Roi.getBounds(pa_x, pa_y, pa_width, pa_height);
if ( ch_x >= pa_x && ch_x <= (pa_x + pa_width) &&
ch_y >= pa_y && ch_y <= (pa_y + pa_height) ) // fast approximation
inBounds = true;
return inBounds;
}
// Function to check for a complete overlap between two regions of interest
function isInRegion(parentRegionIndex, childRegionIndex)
{
// This implementation is faster than using the 'getRegionOverlap' function
// because the for loop checking the overlap can exit prematurely if a single
// pixel from the childRegion is outside of the parentRegion.
inRegion = true;
roiManager("select", childRegionIndex);
Roi.getContainedPoints(ch_xx, ch_yy); // pixels in child region
roiManager("select", parentRegionIndex);
ch_xx_length = ch_xx.length;
for ( i = 0; (inRegion == true) && (i < ch_xx_length); ++i )
{
if ( !Roi.contains(ch_xx[i], ch_yy[i]) ) // child pixel outside parent region
inRegion = false;
}
return inRegion;
}
// Function to make a substack by deleting slices of a stack
function makeSubstack(image, array, name)
{
// The macro command "Make Substack..." exhibits erratic behavior during runtime with custom slice numbers.
// The macro error "Invalid input string" (with value "") is thrown, despite proper initialization and
// formatting of the corresponding input string as documented in the Debug window. Might be a timing issue.
// Arrays with multiple elements can be provided as integers or strings with "newArray(1, "2", 5)".
// However, arrays with single elements can only be provided as strings with "newArray("2")".
if ( (array.length > 0) && (array[0] > 0) )
{
selectWindow(image);
run("Duplicate...", "title=" + v2p(name) + " duplicate"); // mimic "Make Substack..." behavior
for ( i = nSlices; i > 0; --i ) // reverse iterate through slices
{
selectWindow(name); // "Delete Slice" can yield focus to previous window
setSlice(i);
if ( !isInArray(array, i) )
run("Delete Slice", "delete=channel"); // use "delete=slice" for XYCZT-ordered hyperstack
}
}
return name;
}
// Function to merge regions in the ROI Manager
function mergeRegions(array)
{
success = false;
if ( array.length > 0 )
{
roiManager("select", array);
roiManager("combine"); // merge ("OR") disconnected regions
roiManager("add");
success = true;
}
return success;
}
// Function to normalize pixel intensities by their median value
function normalizePixelValues()
{
// The calculation of the median pixel value can be skewed by the abundance of a significant
// amount of pixels with a value of zero (background/non-information), i.e. synthetic images
// from the MIBI or filtered microscope images with large background areas and missing
// background information. We therefore temporarily blank the zero pixels in all images
// before performning the median calculation and the median-based normalization.
setOption("ScaleConversions", false); // keep pixel values during conversion
run("32-bit");
changeValues(0.0, 0.0, NaN); // convert zero background to NaN values
median = getMedian(NaN, NaN);
print("\tInitial median pixel value: " + median); // rounded to value within 0.0001
if ( median > 0.0 && (Math.abs(1.0 - median) > 0.0001) )
{
run("Divide...", "value=" + v2p(median) + " slice");
print("\tUpdated median pixel value: " + getMedian(NaN, NaN));
}
changeValues(NaN, NaN, 0.0); // revert NaN background to zero values
}
// Function to print date and time
function printDateTimeStamp()
{
getDateAndTime(year, month, dayOfWeek, dayOfMonth, hour, minute, second, msec);
print("\n[" + year + "-" + (month + 1) + "-" + dayOfMonth + ", "
+ hour + ":" + minute + ":" + second + "]");
}
// Function to read an image file with Bio-Formats
function readImage(file)
{
// Since we don't know all possible metadata labels for different imaging platforms,
// we've decided to implement a generic pattern matching system that allows us to
// simply add new labels to the list of known labels by extending the prefix list.
// As counting of those metadata labels can be done with or without leading zeros,
// we're using the same mechansim to try different combinations of labels with counts,
// until we get a valid response from the Ext.getMetadataValue function.
counting = ""; // metadata key count subsequential to key
metadataPrefixes = newArray("ChannelName #", "Information|Image|Channel|Name #",
"Name #", "PageName #");
metadataCounting = newArray("0", "01", "1");
countingLength = metadataCounting.length;
prefixesLength = metadataPrefixes.length;
offset = 0; // offset between key and slide numbering
prefix = ""; // metadata key prefix preceeding count
slice = 0; // default "not found" return value from Ext.getMetadataValue()
slices = newArray(0); // labels
sliceCount = 0;
run("Bio-Formats Macro Extensions"); // make Bio-Formats macro extensions available
run("Bio-Formats Windowless Importer", "open=" + v2p(file));
Ext.setId(file); // initializes the given id (file)
Ext.getImageCount(sliceCount);
for ( i = 0; slice == 0 && i < prefixesLength; ++i ) // try different metadata prefixes
{
for ( j = 0; slice == 0 && j < countingLength; ++j ) // try different metadata counts
{
Ext.getMetadataValue(metadataPrefixes[i] + metadataCounting[j], slice);
if ( slice != 0 ) // matching prefix/count pair
{
prefix = metadataPrefixes[i];
counting = metadataCounting[j];
if ( counting == "0" )
offset = -1;
}
}
}
for ( k = 1; k <= sliceCount; ++k ) // extract metadata for each slice
{
setSlice(k);
if ( counting == "01" && k <= 9 ) // Polaris
Ext.getMetadataValue(prefix + "0" + k, slice);
else // MIBI, Vectra, Zeiss
Ext.getMetadataValue(prefix + (k + offset), slice);
if ( slice == 0 ) // no compatible metadata label found
slice = k; // use number instead
setMetadata("Label", slice); // add label to slice
slices = Array.concat(slices, slice);
print("\t" + k + ".) " + slice);
}
setSlice(1); // show first slice
run("Maximize"); // maximize window pane
return slices;
}
// Function to rename an image window
function renameImage(image, title)
{
if ( image == "" )
image = getTitle();
selectWindow(image);
rename(title);
}
// Function to rename a region of interest with ROI Manager
function renameRegion(index, name)
{
roiManager("select", index);
roiManager("rename", name);
roiManager("select", index); // selection lost after renaming
}
// Function to rescale pixel intensities to a custom range
function rescalePixelValues(min_in, max_in, min_out, max_out)
{
// There's a lot of issue that need to be addressed, when rescaling the intensities
// of an image from its initial range to a user-defined range: The code validates
// user input and handles some common cases that we've encountered.
setOption("ScaleConversions", false);
run("32-bit");
tmp = 0.0;
// check input values
if ( isNaN(min_in) )
getRawStatistics(nPixels, mean, min_in, max); // slice, not stack
if ( isNaN(max_in) )
getRawStatistics(nPixels, mean, min, max_in);
if ( (max_in - min_in) < 0.0 ) // swap
{
tmp = min_in;
min_in = max_in;
max_in = tmp;
}
// check output values
if ( isNaN(min_out) )
min_out = 0;
if ( isNaN(max_out) )
max_out = 1;
if ( (max_out - min_out) < 0.0 )
{
tmp = min_out;
min_out = max_out;
max_out = tmp;
}
// work with variable target pixel ranges
difference_in = max_in - min_in;
difference_out = max_out - min_out;
if ( (difference_in > 0.0) && (difference_out > 0.0) )
{
// substract offset from zero, shift left
if ( min_in > 0.0 )
run("Subtract...", "value=" + v2p(min_in) + " slice");
// multiply source range by target range factor
factor = difference_out / difference_in;
run("Multiply...", "value=" + v2p(factor) + " slice");
// add offset from zero, shift right
run("Add...", "value=" + v2p(min_out) + " slice");
}
// adjust final output range and correct numerical errors
getRawStatistics(nPixels, mean, min, max);
if ( min < min_out )
run("Min...", "value=" + v2p(min_out));
if ( max > max_out )
run("Max...", "value=" + v2p(max_out));
// update display range to match new pixel values
updateDisplayRange(NaN, NaN);
}
// Function to save the Log window content
function saveLogFile(file)
{
selectWindow("Log"); //select Log window
saveAs("Text", file);
}
// Function to convert ROIs into grayscale image masks
function setMasksFromRois(image, array)
{
// Mask gray values are derived either from a Region ID or the ROI Manager position.
// To select all regions, simply use the 'Array.getSequence(roiManager("count"))' as
// array - or select specific regions by group, i.e. by 'Roi.getGroup' return value..
// Note: the ROI Manager has to be started before calling this function!
roiManager("UseNames", "true"); // enable full labels
gray = 0;
output = 0;
rois = array.length;
if ( rois > 0 )
{
// create maximum image and adjust output dimensions by cropping
start_width = 8192; // required for absolute values from Roi.getBounds()
start_height = 8192;
end_width = 0;
end_height = 0;
newImage(image, "32-bit black", start_width, start_height, 1);
// crop new image to required minimum size
for ( index = 0; index < rois; ++index )
{
roiManager("select", array[index]);
Roi.getBounds(x, y, width, height); // bounding box dimensions for ROI
tmp_width = x + width;
if ( tmp_width > end_width ) // increase width
end_width = tmp_width;
tmp_height = y + height;
if ( tmp_height > end_height ) // increase height
end_height = tmp_height;
}
makeRectangle(0, 0, end_width, end_height);
run("Crop");
// draw gray values
showStatus("!"); // suppress automatic status updates
for ( index = 0; index < rois; ++index )
{
region = array[index];
roi = parseInt(getRegionID(region)); // get grayscale value from Region ID
if ( !isNaN(roi) )
gray = roi;
else // grayscale value not found
gray = index + 1; // use incrementing grayscale values
roiManager("select", region);
fillRegion(gray);
count = index + 1;
if ( count % 1000 == 0 || count == rois )
showStatus("!Drawing " + count + " out of " + rois + " grayscale masks to image...");
}
run("Select None");
getRawStatistics(pixels, mean, min, max);
updateDisplayRange(min, max);
showStatus(""); // enable status updates
output = max - min;
}
return output;
}
// Function to set id for region of interest name
function setRegionID(index, number)
{
rola = getRegionLabel();
renameRegion(index, toString(number) + delimiter + rola); // avoid "NaN" error with preceeding numeric value
}
// Function to set label for region of interest name
function setRegionLabel(index, string)
{
roid = getRegionID(index);
renameRegion(index, roid + delimiter + string);
}
// Function to substract child regions from a parent region and add it to the ROI Manager
function substractRegions(parentRegionIndex, childRegionIndices)
{
success = false;
childRegionIndicesLength = childRegionIndices.length;
roiManager("select", parentRegionIndex); // parent region
// hint: use 'newArray(a, b, c)' to substract regions a, b, and c from the parent region,
// and use 'newArray(toString(d))' to substract a single region, d, from the parent region
for ( i = 0; i < childRegionIndicesLength; ++i ) // child regions
{
setKeyDown("alt"); // simulate pressing the ALT key (down position)
roiManager("select", childRegionIndices[i]); // substract
}
setKeyDown("none"); // release all keys (up position)
if ( selectionType() != -1 ) // function returns -1 if there is no selection left
{
roiManager("add");
success = true;
}
return success;
}
// Function to toggle the batch mode on/off or show/hide images while in batch mode
function toggleBatchMode(useBatchMode, temporary)
{
// The ROI Manger seems to ignore the batch mode flag: In contrast, the Results
// table is not updated when measuring in batch mode. It turns out that most of
// the computational resources required by the ROI Manager are due to frequent
// display updates during region manipulation: By minimizing the ROI Manager
// window, the CPU load drops significantly. However, window decorators are
// OS-accessible only. Luckily, we can resize the ROI Manager to 0x0 pixels,
// effectively minimizing the window and preventing frequent window redraws.
withRoiManager = isAvailableWindow("ROI Manager");
if ( withRoiManager )
{
roiManWidth = 197; // default Windows values
roiManHeight = 285;
downShift = 0; // top
rightShfit = screenWidth - roiManWidth; // right
}
if ( useBatchMode )
{
if ( is("Batch Mode") ) // batch mode is already active
{
if ( temporary )
setBatchMode("show"); // displays the active hidden image, while batch mode remains in same state
else
{
print("\tExiting batch mode...");
setBatchMode("exit and display"); // exits batch mode and displays all hidden images
setBatchMode(false); // force immediate exit
if ( withRoiManager )
{
print("\tRestoring ROI Manager...");
Table.setLocationAndSize(rightShfit, downShift, roiManWidth, roiManHeight, "ROI Manager");
}
}
}
else // batch mode not yet active
{
if ( temporary )
setBatchMode("hide"); // enters (or remains in) batch mode and hides the active image
else
{
if ( withRoiManager )
{
print("\tMinimizing ROI Manager...");
Table.setLocationAndSize(rightShfit, downShift, 0, 0, "ROI Manager");
}
print("\tEntering batch mode...");
setBatchMode(true); // enter batch mode and don't display newly opened images
}
}
}
}
// Function to update the displayed range
function updateDisplayRange(min_in, max_in)
{
// Update the display range without manipulating the pixel intensities.
min_out = min_in;
max_out = max_in;
if ( isNaN(min_in) || isNaN(max_in) )
{
getRawStatistics(nPixels, mean, min, max); // slice, not stack
if ( isNaN(min_in) )
min_out = min;
if ( isNaN(max_in) )
max_out = max;
}
setMinAndMax(min_out, max_out);
}
// Function to convert a value to a parameter string
function v2p(value)
{
// This is a workaround for "undefined variable" errors when using
// the address operator (&) in functions' parameter assignments.
// By converting the numeric value to a string, we also avoid
// string concatenation problems during parameter parsing.
string_value = toString(value);
if ( isNaN(string_value) ) // value is non-numeric
return "[" + value + "]";
else
return "[" + string_value + "]"; // value is numeric
}
// Function to wait for a certain file to be deleted
function waitForFileDeletion(file)
{
// Network drives might be slow or files might be locked, i.e. opened in
// another application and not accessible for deletion. We're therefore
// notifying the user and waiting until the lock has been removed.
notified = false;
while ( File.exists(file) )
{
deleted = File.delete(file);
if ( deleted != 1 && !notified ) // deleting failed, notify user
{
print("\tCan't delete file. Close other programs accessing the file.");
notified = true;
}
wait(1000); // ms
}
}
// Function to wait for a window with a specific title
function waitForWindow(title)
{
// Wait for computationally expensive calculations to finish by
// waiting for the result window to appear. This is better than
// waiting for a fixed amount of time with the risk of not having
// waited for long enough and failing continuation of the program.
while ( !startsWith(getTitle(), title) ) // title of the current batch mode image
{
wait(500); // ms
}
}