-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLibrary.txt
543 lines (483 loc) · 16.6 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
/* 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 <[email protected]>
* 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.53e"); // minimum ImageJ version
/*
* Variables
*/
// global, preset for macros
var libraryVersion = "CU-MacroLibrary v1.00 (2021-05-31)";
// local, overwritten by macros
array = newArray(0);
blue = 0;
childRegionIndices = newArray(0);
childRegionIndex = 0;
counts = 0;
file = "";
green = 0;
group = 0;
image = "";
index = 0;
max = 0;
max_in = 0;
max_out = 0;
min = 0;
min_in = 0;
min_out = 0;
name = "";
parentRegionIndex = 0;
red = 0;
size = 0;
string = "";
suffixes = newArray("");
temporary = true;
title = "";
unit = "pixel";
useBatchMode = false;
value = 0;
versionString = "";
/*
* Start
*/
print(libraryVersion);
/*
* Functions
*/
// Function to substract child regions from a parent region and add it to the ROI Manager
function addRemainderRegion(parentRegionIndex, childRegionIndices)
{
success = false;
childRegionIndicesLength = childRegionIndices.length;
roiManager("select", parentRegionIndex); // 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 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");
}
// 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 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, max)
{
updateDisplayRange(NaN, NaN); // force pixel values update
if ( isNaN(min) || isNaN(max) )
{
getRawStatistics(nPixels, mean, min, max);
setThreshold(min, max);
output = getValue("Median raw limit");
resetThreshold();
}
else
output = getValue("Median raw");
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 return relative overlap between two regions of interest
function getRegionOverlap(parentRegionIndex, childRegionIndex)
{
overlap = 0; // track overlap of roi with region in percent
roiManager("select", childRegionIndex);
Roi.getContainedPoints(roi_xx, roi_yy); // pixels inside roi
roi_xx_length = roi_xx.length;
roiManager("select", parentRegionIndex);
for (p = 0; p < roi_xx_length; ++p) // iterate through roi pixels
{
if ( Roi.contains(roi_xx[p], roi_yy[p]) ) // roi pixel inside region
overlap++;
}
overlap = Math.round(overlap / roi_xx_length * 100);
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 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()
{
print("\\Clear"); // clear Log window
printDateTimeStamp();
print("ImageJ2 v" + IJ.getFullVersion);
print(versionString);
run("Close All"); // close all image windows
}
// 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 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 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, toString(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 catches some common issus that we've encountered.
setOption("ScaleConversions", false);
run("32-bit");
// check user input
if ( isNaN(min_in) || isNaN(max_in) ) // get extrema from image values
getRawStatistics(nPixels, mean, min_in, max_in);
difference_in = max_in - min_in;
if ( difference_in <= 0.0 ) // invalid denominator for target range factor
{
if ( difference_in == 0.0 ) // image is monochromatic, do not correct offset
min_in = 0.0;
difference_in = 1.0; // ignore value for target range factor calculation
}
if ( isNaN(min_out) || isNaN(max_out) ) // set arbitrary values
{
min_out = 0.0;
max_out = 1.0;
}
difference_out = max_out - min_out;
// work with variable target pixel ranges
if ( 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");
// 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));
}
// work with fixed target pixel values
else if ( max_out == 255 || max_out == 65535 || max_out == 1e30 ) // max values
run("Set...", "value=" + v2p(max_out));
else if ( min_out == 0 ) // min value
run("Set...", "value=" + v2p(min_out));
else // arbitrary value
run("Set...", "value=" + v2p(max_out));
updateDisplayRange(NaN, NaN);
}
// Function to save the Log window content
function saveLogFile(file)
{
selectWindow("Log"); //select Log window
saveAs("Text", file);
}
// 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 prevent window updates.
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
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, max)
{
// Update the display range without manipulating the pixel intensities.
if ( isNaN(min) || isNaN(max) )
getRawStatistics(nPixels, mean, min, max); // slice, not stack
setMinAndMax(min, max);
}
// 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.
return "[" + toString(value) + "]";
}
// 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
}
}