-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathQuanty-cFOS_v0.ijm
2277 lines (1609 loc) · 71.5 KB
/
Quanty-cFOS_v0.ijm
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
/* e##########################################################################################################################
* Project: Semi/Automated 2D cell counting with cFOS intansity threshold optimization
* [ Prof Rohini Kuner and Heidelberg Pain Consortium (SFB 1158) ]
*
* Developed by Dr. Carlo Antonio Beretta
* Institute of Pharmacology and Department for Anatomy and Cell Biology @ Heidelberg University
* Email: [email protected]
*
* Description:
* User can choose different methods to count in 2D positive cells in section.
* The tool is optimized to count cFOS positive cells. The idea is to compute the z-score for the intensity values of detected cells on
* a specified amount of images and use these values as cutoff to decide positive and false positive cFOS cells.
* User can specify two input folders with the raw images and the pre-processed images or use the 2D StarDist Versatile (fluorescent nuclei) model to
* segment the cell in 2D. In this case only one folder will be the input for the Quanty-cFOS script.
* With few changes in the code the user can also load a specific model pretrained on his/her own data.
*
* To DO:
*
* > Batch Processing with Threshold PM Preview Mode
* > Cutoff size above filter size
*
* ##########################################################################################################################
*/
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%% Functions %%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// #################################################
// StartUp Functions
// # 1
function Setting() {
// Set the Measurements parameters
run("Set Measurements...", "area mean center perimeter limit redirect=None decimal=8");
// Set binary background to 0
run("Options...", "iterations=1 count=1 black");
// General color setting
run("Colors...", "foreground=white background=black selection=yellow");
}
// # 2
// Close all the open images
function CloseAllWindows() {
while (nImages > 0) {
selectImage(nImages);
close();
}
}
// # 3
// Screen location
function ScreenLocation() {
imageWidth = getWidth();
imageHeight = getHeight();
imageReshapeWidth = screenWidth *0.5;
imageReshapeHeight = imageWidth *10;
imageShape = newArray(imageReshapeWidth, imageReshapeHeight);
return imageShape;
}
// # 4
// Choose the input directories (Raw and Preprocessed images)
function InputDirectoryRawPM(userOutput) {
if (userOutput[0] == true && userOutput[1] == false) {
dirInRaw = getDirectory("Please choose the input root directory with the RAW images");
dirInPreProcess = getDirectory("Please choose the input root directory with the PREPROCESSED images");
// The macro check that you choose a directory and output the input path
if (lengthOf(dirInRaw) == 0 || lengthOf(dirInPreProcess) == 0) {
exit("Exit");
} else {
// Output the path
text = "\nInput Raw path:\t" + dirInRaw;
print(text);
text = "Input Preprocessed path:\t" + dirInPreProcess;
print(text);
inputPath = newArray(dirInRaw, dirInPreProcess);
return inputPath;
}
} else if (userOutput[0] == false && userOutput[1] == true) {
dirInRaw = getDirectory("Please choose the input root directory with the RAW images");
// The macro check that you choose a directory and output the input path
if (lengthOf(dirInRaw) == 0) {
exit("Exit");
} else {
// Output the path
text = "\nInput Raw path:\t" + dirInRaw;
print(text);
inputPath = dirInRaw;
return inputPath;
}
}
}
// # 5a
// Output directory
function OutputDirectory(outputPath, year, month, dayOfMonth, second) {
// Use the dirIn path to create the output path directory
dirOutRoot = outputPath;
// Change the path
lastSeparator = lastIndexOf(dirOutRoot, File.separator);
dirOutRoot = substring(dirOutRoot, 0, lastSeparator);
// Split the string by file separator
splitString = split(dirOutRoot, File.separator);
for(i=0; i<splitString.length; i++) {
lastString = splitString[i];
}
// Remove the end part of the string
indexLastSeparator = lastIndexOf(dirOutRoot, lastString);
dirOutRoot = substring(dirOutRoot, 0, indexLastSeparator);
// Use the new string as a path to create the OUTPUT directory.
dirOutRoot = dirOutRoot + "MacroResults_" + year + "-" + (month+1) + "-" + dayOfMonth + "_0" + second + File.separator;
return dirOutRoot;
}
// # 5b
// When bacth is enabled we additional save the labeled images in a common directory to facilitate further processing
function GroupLableImages(dirOutRoot, title, i, batch) {
if (batch == false) {
// Check if the output directory already exists
if (File.exists(dirOutRoot)) {
// Create the image and the analysis output directory inside the output root directory
dirOut = dirOutRoot + "0" + (i+1) + "_" + title + File.separator;
File.makeDirectory(dirOut);
}
dirOutLabels = "";
saveImages = newArray(dirOutRoot, dirOut, dirOutLabels);
} else if (batch == true) {
// Check if the output directory already exists
if (File.exists(dirOutRoot)) {
if (i == 0) {
// Create the image and the analysis output directory inside the output root directory
dirOutLabels = dirOutRoot + "LabeledImages" + File.separator;
File.makeDirectory(dirOutLabels);
// Create the image and the analysis output directory inside the output root directory
dirOut = dirOutRoot + "0" + (i+1) + "_" + title + File.separator;
File.makeDirectory(dirOut);
} else {
// Create the image and the analysis output directory inside the output root directory
dirOut = dirOutRoot + "0" + (i+1) + "_" + title + File.separator;
File.makeDirectory(dirOut);
}
}
saveImages = newArray(dirOutRoot, dirOut, dirOutLabels);
}
return saveImages;
}
// # 6
// Open the ROI Manager
function OpenROIsManager() {
if (!isOpen("ROI Manager")) {
run("ROI Manager...");
} else {
if (roiManager("count") == 0) {
print("Warning! ROI Manager is already open and it is empty");
} else {
print("Warning! ROI Manager is already open and contains " + roiManager("count") + " ROIs");
print("The ROIs will be deleted!");
roiManager("reset");
}
}
}
// # 7
// # Main user input setting
function UserInput() {
ilastikPM = true;
starDist = false;
tails = 1; // Deafult 1
batch = false;
optIntSteps = 3;
Dialog.create("Main Setting Window");
Dialog.addMessage("Quanty-cFOS for Semi-Automated Fos/c-fos Cells Counting & Beyond", 18);
Dialog.addMessage("____________________________________________________________________________");
Dialog.addCheckbox("Use Pre-Processed Image (ilastik Pixel Classification)", ilastikPM);
Dialog.addCheckbox("Run StarDist 2D (Versatile - Fluorescent Nuclei)", starDist);
Dialog.addToSameRow();
Dialog.addNumber("StarDist Tails Number", tails);
Dialog.addMessage(" _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _");
Dialog.addMessage("\n");
Dialog.addCheckbox("Batch Analysis", batch);
Dialog.addToSameRow();
Dialog.addNumber("Optimization Steps (N. Images)", optIntSteps);
Dialog.addMessage("____________________________________________________________________________");
Dialog.addMessage("\n*Quanty-cFOS.ijm tool has been initially developed for Prof Rohini Kuner's lab members\n and the Heidelberg Pain Consortium (SFB 1158 - https://www.sfb1158.de)", 11, "#001090");
Dialog.addMessage(" **Last Update: 2022-11-16", 11, "#001090");
Dialog.addMessage(" ***Please cite the paper if you are using the Quanty-cFOS tool in your research: <<In preparation>>", 11, "#001090");
// Add Help button
html = "<html>"
+ "<style> html, body { width: 500; height: 350; margin: 10; padding: 0; border: 0px solid black; background-color: #ECF1F4; }"
+ "<h1> <center> 🐀 Quanty-cFOS 🐀 </center> </h1>"
+ "<h3> <section> "
+ "<b> Options:</b>"
+ "<li><i>Preprocessed Images</i>: [INPUT] Choose the input directory with the raw images and the input directory with the pre-processed images. More about <a href=https://www.ilastik.org/documentation/pixelclassification/pixelclassification><i>ilastik pixel classification</i></a><br/><br/></li>"
+ "<li><i>Run <a href=https://imagej.net/StarDist> StarDist 2D</a></i>: [INPUT] Choose the input directory with the raw images! The pre-trained StarDist versatile fluorescent 2D model is used for cell segmentation."
+ " Increase the <b> StarDist Tails Number </b> in case of out-of-memory errors. <i><b>NB:</i></b> Higher the number of tails slower is the process! <br/><br/></li>"
+ "<li><i>Batch Analysis</i>: User can decide to process the input images one-by-one with a specific intensity cutoff or process the input images using the same intensity cutoff <br/><br/></li>"
+ "<li><i>Optimization Steps</i>: Number of images used to compute the intensity threshold cutoff value."
+ " NB: User should exclude these images from the final Fos/<i>c-fos</i> counting or reprocess the images using the computed intensity cutoff. Check the LOG file to find the value used<br/><br/></li>"
+ "</h3> </section>"
+ "</style>"
+ "</html>";
Dialog.addHelp(html);
Dialog.show();
ilastikPM = Dialog.getCheckbox();
starDist = Dialog.getCheckbox();
tails = Dialog.getNumber();
batch = Dialog.getCheckbox();
optIntSteps = Dialog.getNumber();
// Uncheck the Pre-Processing method in case the user select StarDist detection
if (ilastikPM == true && starDist == true) {
ilastikPM = false;
starDist = true;
showMessage("Warning", "<html>"
+ "<style> html, body { width: 600; height: 80; margin: 5; padding: 0; background-color: #ECF1F4; }"
+"<h4><br><font size=+0.5><font color=red>🚫 INVALID INPUT SETTINGS</font color></font size></br></h4>"
+"<br>You choose to run <b><i>Pre-Processed Images & Run StarDist 2D</b></i></br>"
+"<br>> Running <b><i>StarDist 2D (Versatile -Fluorescent Nuclei)</b></i></br>"
+ "</style>"
+"</html>");
}
// Check if the user set the optimization step to zero (NOT VALIDE CHOICE)
if (optIntSteps == 0) {
setOptStep = optIntSteps;
optIntSteps = 1;
showMessage("Warning", "<html>"
+ "<style> html, body { width: 600; height: 80; margin: 5; padding: 0; background-color: #ECF1F4; }"
+"<h4><br><font size=+0.5><font color=red>🚫 INVALID INPUT SETTINGS</font color></font size></br></h4>"
+"<br>The number of Optimization Steps must be <b><i>>= 1</b></i></br>"
+"<br>> Setting step size to <b><i>1</b></i></br>"
+ "</style>"
+"</html>");
}
userOutput = newArray(ilastikPM, starDist, tails, batch, optIntSteps);
return userOutput;
}
// # 8
// Input user setting
function InputDialog(title) {
roiName = "cFOS-Positive";
process2D = true;
process3D = false;
cFOS = true;
sigma = 3;
usercFOSThreshold = false;
processSubRegions = false;
previewMode = false;
Dialog.create("User Input Setting Window");
Dialog.addString("RoiManger ROIs Tag:", roiName, 90);
Dialog.addCheckbox("2D Analysis", process2D);
Dialog.addToSameRow();
Dialog.addCheckbox("3D Analysis (Not Implemented)", process3D);
Dialog.addCheckbox("Automated Optimization (Experimental)", cFOS);
Dialog.addToSameRow();
Dialog.addNumber("Sigma", sigma);
Dialog.addCheckbox("Manual Optimization", usercFOSThreshold);
Dialog.addCheckbox("Select Multiple Sub-Brain Regions", processSubRegions);
Dialog.addToSameRow();
Dialog.addCheckbox("Allow Preview User Setting (Raw & Pre-Processed Input)", previewMode);
// Add Help button
html = "<html>"
+ "<style> html, body { width: 500; height: 600; margin: 10; padding: 0; background-color: #ECF1F4; }"
+ "<h1> 🔧 Help: </h1>"
+ "<h3> <section>"
+ "<b> User Input Setting:</b>"
+ "<li><i>Image Tag: </i>RoiManger ROIs name used for Fos/<i>c-fos</i> positive cells<br/><br/></li>"
+ "<li><i>2D Analysis: </i>Single slices or Maximum Intensity Projections<br/><br/></li>"
+ "<li><i>3D Analysis: </i>Not implemented<br/><br/></li>"
+ "<li><i>Automated Optimization</i> <b>(∑ MeanIntensity / nROIs)</b>: compute the mean intensity value and the standard deviation of all ROIs."
+ " <b>[Assumption Normal Distribution]<b/> the z-score <b>(z = χ - μ / σ)</b> is computed for each ROI and used to calculate the intensiy cutoff for Fos<i>/c-fos</i> positive and negative neurons."
+ " The sigma value can be modified to increase or decrease the intensity cutoff [e.g.: 3]. Counts validation can be performed using ground truth images<br/><br/></li>"
+ "<li><i>Manual Optimization: </i>user can manually enter the intensity cutoff value to count Fos/<i>c-fos</i> positive"
+ " and negative neurons (positive cells above the intensity threshold / negative cells below the intensity threshold)<br/><br/></li>"
+ "<li><i>All Cell Count: </i>Uncheck the automated and manual optimization boxes if your goal is to count the total number of cells in the images."
+ " The optimization steps function is not used<br/><br/></li>"
+ "<li><i>Select Multiple Sub-Brain Regions: </i>user can select and process many regions in the same input image one-by-one<br/><br/></li>"
+ "<li><i>Preview Mode: </i> user can visualize the image to threshold, test different threshold methods and measure the area of "
+ "the cells to detect. This information can be used as input for the cells segmentation in the Preview Dialog box (Not supported for StarDist)<br/><br/></li>"
+ "</h3> </section>"
+ "</style>"
+ "</html>";
Dialog.addHelp(html);
Dialog.show();
roiName = Dialog.getString();
process2D = Dialog.getCheckbox();
process3D = Dialog.getCheckbox();
cFOS = Dialog.getCheckbox();
sigma = Dialog.getNumber();
usercFOSThreshold = Dialog.getCheckbox();
processSubRegions = Dialog.getCheckbox();
previewMode = Dialog.getCheckbox();
// Uncheck the automated method in case the user select the manual method
// This is in case the user wants to processed the images manualy and forget to uncheck the automated method
if (cFOS == true && usercFOSThreshold == true) {
cFOS = false;
usercFOSThreshold = true;
showMessage("Warning", "<html>"
+ "<style> html, body { width: 600; height: 80; margin: 5; padding: 0; background-color: #ECF1F4; }"
+"<h4><br><font size=+0.5><font color=red>🚫 INVALID INPUT SETTINGS</font color></font size></br></h4>"
+"<br>You choose to run <b><i>Automated Optimization & Manual Optimization</b></i></br>"
+"<br>> Running <b><i>Manual Optimization</b></i></br>"
+ "</style>"
+"</html>");
}
outputDialog = newArray(roiName, process2D, process3D, cFOS, usercFOSThreshold, processSubRegions, previewMode, sigma);
return outputDialog;
}
// # 9
// Check for StarDist installation
function CheckStarDistInstallation() {
List.setCommands;
if (List.get("StarDist 2D") != "" && List.get("N2V predict") != "") {
print("> StarDist 2D and CSBDeep are installed!");
wait(1000);
print("\\Clear");
} else {
showMessage("Warning", "<html>"
+ "<style> html, body { width: 800; height: 80; margin: 5; padding: 0; background-color: #ECF1F4; }"
+"<h4><br><font size=+0.5>🛠 Before to start to use the Quanty-cFOS tool you need to install the <i>StarDist 2D</i> and <i>CSBDeep plugins</i></font size></br></h4>"
+"<br><li>Select <i>Help >> Update...</i> from the main ImageJ/Fiji window to start the updater</li></br>"
+"<br><li>Click on <i>Manage update sites</i> This brings up a dialog menu where you can activate additional update sites</li></br>"
+"<br><li>Check the <i>StarDist</i> and the <i>CSBDeep</i> checkboxes and close the dialog. Now you should see additional .jar file ready to be installed</li></br>"
+"<br><li>Click <i>Apply changes</i> and restart ImageJ/Fiji</li></br>"
+"<br><li>After restarting ImageJ/Fiji you should be able to run the Quanty-cFOS with StarDist 2D option enabled</li></br>"
+ "</style>"
+"</html>");
exit();
}
}
// # 10
// Create Intensity Threshold values plot
function PlotOptimizationValueInt(optIntArray, intensityCutOff, optIntSteps, reduceNaN) {
Plot.create("Intensity Threshold Optimization Cutoff", "Optimization Steps", "Intensity Threshold");
Plot.setColor("red");
Plot.setBackgroundColor("#ECF1F4");
//Plot.setLimitsToFit();
Plot.setLimits(-1, (optIntSteps+reduceNaN), 0, 255);
Plot.add("line", optIntArray);
Plot.add("diamond", optIntArray);
Plot.setColor("black");
Plot.setFontSize(18);
Plot.addText("*Opt. Int. Cutoff: " + intensityCutOff, 0.45, 0.5);
Plot.setLineWidth(8);
}
// # 11
// Check input image bit depth
// It is supported only 8 bit raw images
// User can edit this part and process images with different bit depth but without any warranty (never tested)
function CheckBitDepth() {
// Catch raw image bit depth
inputBitDepth = bitDepth();
if (inputBitDepth == 16 || inputBitDepth == 32 || inputBitDepth == 24) {
setBatchMode(true);
exit("Input must be 8 bit!\nThe input image is " + inputBitDepth + " bit");
} else {
print("Input Image is " + inputBitDepth + " bit\t: Passed");
}
}
// #################################################
// Analysis Functions
// # 1
// Check if the input raw image is a single channel image
// Only single channel images are supported
function CheckNumberOfCh(titleRaw, titlePreProcess) {
// Raw
selectImage(titleRaw);
// Get image dimensions
getDimensions(width, height, channels, slices, frames);
if (channels == 1) {
print("Raw Input Image Channel Test [Ch0" + channels + "]\t: Passed" );
} else {
// Display the input image
setBatchMode(false);
// Output the error message
exit("Multi-Channels RAW Images are NOT supported!");
}
// PM
selectImage(titlePreProcess);
// Get image dimensions
getDimensions(width, height, channels, slices, frames);
if (channels == 1) {
print("Pre-porcessed Images Channel Test [Ch0" + channels + "]\t: Passed" );
} else {
// Display the input image
setBatchMode(false);
// Output the error message
exit("Multi-Channels Pre-porcessed Images are NOT supported!");
}
}
// # 2
// Compute the MIP
function ComputeStack(inputTitleRaw, inputTitlePreProcess, process2D, process3D) {
// Raw
selectImage(inputTitleRaw);
// Get image dimensions
getDimensions(width, height, channels, slices, frames);
if (slices > 1 && process2D == true && process3D == false) {
// Compute the MIP
run("Z Project...", "projection=[Max Intensity]");
// Get MIP title
titleRaw = getTitle();
// Close the input raw image
selectImage(inputTitleRaw);
close(inputTitleRaw);
} else if (slices > 1 && process2D == false && process3D == true ) {
// Run the 3D analysis (Not implemented)
} else {
// The input image is already a MIP or the user choose the 3D analysis
titleRaw = getTitle();
}
// PM
selectImage(inputTitlePreProcess);
// Get image dimensions
getDimensions(width, height, channels, slices, frames);
if (slices > 1 && process2D == true && process3D == false) {
// Compute the MIP
run("Z Project...", "projection=[Max Intensity]");
// Get MIP title
titlePreProcess = getTitle();
// $$$$$$$$ To Test $$$$$$$$
run("Median...", "radius=3");
// Close the input PM image
selectImage(inputTitlePreProcess);
close(inputTitlePreProcess);
} else if (slices > 1 && process2D == false && process3D == true) {
// Run the 3D analysis (Not implemented)
} else {
// The input image is already a MIP or the user choose the 3D analysis
titlePreProcess = getTitle();
// $$$$$$$$ To Test $$$$$$$$
run("Median...", "radius=3");
}
inputTitle = newArray(titleRaw, titlePreProcess);
return inputTitle;
}
// # 3
// Print summary function (Modified from ImageJ/Fiji Macro Documentation)
function sfprintsf(textSummary) {
titleSummaryWindow = "Summary Window";
titleSummaryOutput = "["+titleSummaryWindow+"]";
outputSummaryText = titleSummaryOutput;
if (!isOpen(titleSummaryWindow)) {
// Create the results window
run("Text Window...", "name="+titleSummaryOutput+" width=90 height=20 menu");
// Print the header and output the first line of text
print(outputSummaryText, "% Input Image File Name\t" + "% ROI Name Selected\t" + "% Total Number of Cells Counted\t" + "% Fos/c-fos Positive Cells Counted (above cutoff)\t" + "% Fos/c-fos Negative Cells Counted (below cutoff)\t" + "% Intensity Cutoff\t" + "% Area Cutoff" + "\n");
print(outputSummaryText, textSummary +"\n");
// Minimize the Summary window
eval("script","f = WindowManager.getFrame('Summary Window'); f.setLocation(0,0); f.setSize(10,10);");
} else {
print(outputSummaryText, textSummary +"\n");
}
}
// # 4
// Store the center of mass of each detected object in a table
function GetCenterOfMass() {
// Run measure
roiManager("deselect");
roiManager("show none");
roiManager("show all with labels");
roiManager("Measure");
// Preallocate variables
xM = newArray(nResults);
yM = newArray(nResults);
mean = newArray(nResults);
cFOS_State = newArray(nResults);
if (nResults != 0) {
for (row = 0; row < nResults; row++) {
xM[row] = getResult("XM", row);
yM[row] = getResult("YM", row);
mean[row] = getResult("Mean", row);
if (mean[row] > 60) {
mean[row] = 1;
cFOS_State[row] = "Positive";
} else {
mean[row] = 4;
cFOS_State[row] = "Negative";
}
}
// Create a summary table with the X and Y center of mass coordinate of each detected object
Table.create("CentroidArray");
Table.setLocationAndSize(0, 0, 1, 1);
Table.setColumn("XM", xM);
Table.setColumn("YM", yM);
Table.setColumn("ID", mean);
Table.setColumn("State", cFOS_State);
// Save and close the table
Table.save(dirOut + "CenterOfMass_" + title + "_ROI_0" + nSubregion + ".csv");
// Close the results table and the center of mass table
selectWindow("Results");
run("Close");
selectWindow("CentroidArray");
run("Close");
}
}
// # 5
// The user can specify the best threshold and the lower size of the objects to segment (area in pixel^2 or um^2)
// It works only with pre-processed option
function PreviewSetting() {
// User can choose the best threshold and the object size
run("Threshold...");
setTool("oval");
// User can enter the best threshold test it and the area in pixel^2
thresholdType = "Default";
pixelArea = 30;
Dialog.createNonBlocking("User Settings...");
Dialog.addString("Threshold type", thresholdType, 30);
Dialog.addNumber("Process cells larger then: (Area / in pixels^2)", pixelArea)
// Add Help button
html = "<html>"
+ "<style> html, body { width: 500; height: 250; margin: 10; padding: 0; background-color: #ECF1F4; }"
+ "<h2> 🔧 Help: </h2>"
+ "<h3>"
+ "<b> <br/>User Input Setting:<br/> </b>"
+ "<li> <i>Intensity Threshold: </i> User can test different thresholds for cell segmentation </li>"
+ "<li> <i>Min Size (pixel^2): </i> Check the size of your cells by drawing a circle around the cell and press 'M' to measure the area </li>"
+ "</h3>"
+ "</style>"
+ "</html>";
Dialog.addHelp(html);
Dialog.show();
pixelArea = Dialog.getNumber();
thresholdType = Dialog.getString();
userSetting = newArray(thresholdType, pixelArea);
// Close the results window and the threshold window
if (isOpen("Results")) {
// Close the results image
selectWindow("Results");
run("Close");
}
if (isOpen("Threshold")) {
// Close the results image
selectWindow("Threshold");
run("Close");
}
// Clear selection
run("Select None");
// Return the user setting
return userSetting;
}
// # 6
// Automated threshold optimization for intensity and cell area
function AutomatedThresholdEstimation(sigma, nSubregion) {
// Compute the mean intensity value for cFOS positive segemneted cells
selectImage(titleRaw);
if (nSubregion == 0) {
run("Median...", "radius=2");
}
// ROI Manager length
count = roiManager("count");
// Initialize variable
sumIntValue = 0;
sumArea = 0;
meanAreaArray = newArray(count);
meanArrayIntensity = newArray(count);
sumPwerMeanInt = 0;
sumPwerMeanArea = 0;
if (count > 0) {
for (jj = 0; jj < roiManager("count"); jj++) {
// Select each ROI in the roiManger
roiManager("select", jj);
// Measure the mean intensity and area in the ROI
List.setMeasurements(jj);
getMeanIntValue = List.getValue("Mean");
getMeanArea = List.getValue("Area");
sumIntValue += getMeanIntValue;
meanArrayIntensity[jj] = getMeanIntValue;
sumArea += getMeanArea;
meanAreaArray[jj] = getMeanArea;
// Clear the list
List.clear();
}
// Compute the std of the intensity and area
meanInt = sumIntValue / (count+1);
meanArea = sumArea / (count+1);
for (ss = 0; ss < roiManager("count"); ss++) {
diffMeanInt = meanArrayIntensity[ss] - meanInt;
powerMeanInt = pow(diffMeanInt, 2);
sumPwerMeanInt += powerMeanInt;
diffMeanArea = meanAreaArray[ss] - meanArea;
powerMeanArea = pow(diffMeanArea, 2);
sumPwerMeanArea += powerMeanArea;
}
// Check point
intensitySTD = sqrt(sumPwerMeanInt / count);
areaSTD = sqrt(sumPwerMeanArea / count);
// Mean intensity z scopre analysis (zScore = Xi - U / S)
// Mean area on two fold the std
positiveScore = 0;
countPositiveInt = 0;
sumSignScore = 0;
countPositiveArea = 0;
twoSTDAreaCutOff = 0;
for (zz = 0; zz < roiManager("count"); zz++) {
zScore = (meanArrayIntensity[zz] - meanInt) / intensitySTD;
if ((zScore > (sigma*-1) && zScore < sigma) && meanAreaArray[zz] <= 2*areaSTD) {
countPositiveInt += 1;
positiveScore += meanArrayIntensity[zz];
sumSignScore += zScore;
if (meanAreaArray[zz] <= areaSTD) {
countPositiveArea += 1;
twoSTDAreaCutOff += meanAreaArray[zz];
}
// In case the objs area of all cells is above the area STD use the area STD as cutoff
if (countPositiveArea == 0) {
countPositiveArea = 1;
twoSTDAreaCutOff = areaSTD;
}
}
/*
if (meanAreaArray[zz] <= areaSTD) {
countPositiveArea += 1;
twoSTDAreaCutOff += meanAreaArray[zz];
}
// In case the objs area of all cells is above the area STD use the area STD as cutoff
if (countPositiveArea == 0) {
countPositiveArea = 1;
twoSTDAreaCutOff = areaSTD;
}
*/
}
// Output the cutoff for intensity and area
intensityCutOff = positiveScore / countPositiveInt;
probabiltyScore = sumSignScore / countPositiveInt;
areaCutOff = twoSTDAreaCutOff / countPositiveArea;
/*
// Output the z score probability for the value in the range
if (probabiltyScore > 0) {
print("z-score intensity probability:", 1 - probabiltyScore);
} else if (probabiltyScore < 0) {
print("z-score intensity probability:", 1 - sqrt(pow(probabiltyScore, 2)));
} else {
print("z-score intensity probability:", 1);
}
*/
}
cutOffValues = newArray(intensityCutOff, areaCutOff);
return cutOffValues;
}
// # 7 (TO OPTIMIZE)
// Count cells in 2D
function CellCount2D(cFOS, usercFOSThreshold, title, roiName, width, height, slices, titleRaw, dirOut, dirOutRoot, nSubregion, thresholdType, smallerObjSize, batch, i, optIntArray, optAreaArray, optIntSteps, sigma, reduceNaN) {
// Select preprocessed image
// The last active image in the macro
// dirOutRoot is passed but not used.
// Threshold the image in case the user chose ilastikPM
if (userOutput[0] == true && userOutput[1] == false) {
// Remove ROIs
run("Select None");
// HERE WE COULD USE SOMTHING MORE ACCURATE
// Simple thresholding of the ilastik probability map to generate a binary image
setAutoThreshold(thresholdType + " dark");
setOption("BlackBackground", true);
run("Convert to Mask");
// Binary operations
run("Fill Holes");
run("Watershed");
// Get the positive cells and create a new image
// Change this to highObjSize enter by the user
run("Analyze Particles...", "size=["+smallerObjSize+"]-["+smallerObjSize*5+"] exclude clear add");
newImage("clear", "8-bit black", width, height, slices);
roiManager("Show None");
roiManager("Show All");
roiManager("Fill");
// Threshold ilatik PM for cFOS analysis
selectedTitle = getTitle();
selectImage(selectedTitle);
} else if (userOutput[0] == false && userOutput[1] == true) {
// Remove ROIs
run("Select None");
// StarDist input for cFOS analysis
run("Duplicate...", "title=stardistRunningImage");
selectedTitle = getTitle();
selectImage(selectedTitle);
}
// # Condition 1
if (cFOS == true && usercFOSThreshold == false) {
count = roiManager("count");
// Initialize Variables
cFOSPositive = 0;
cFOSFalsePoistive = 0;
if (count > 0) {
// Store the center of mass of each detected object in a table and save the table
// GetCenterOfMass();
// Compute automated mean intensity cutoff value (see batch processing and optimization steps)
if (batch == false) {
cutOffValues = AutomatedThresholdEstimation(sigma, nSubregion);
intensityCutOff = cutOffValues[0];
areaCutOff = cutOffValues[1];
print("Optimization_ " + "ROI0-" + nSubregion + " Automated Mean Intensity CutOff:\t" + intensityCutOff + " - Sigma value equal to: " + sigma);
print("Optimization_ " + "ROI0-" + nSubregion + " Automated Area CutOff:\t" + areaCutOff);
} else if (batch == true) {
if (i < optIntSteps) {
cutOffValues = AutomatedThresholdEstimation(sigma, nSubregion);
intensityCutOff = cutOffValues[0];
areaCutOff = cutOffValues[1];
//optIntArray[i] = intensityCutOff;
//optAreaArray[i] = areaCutOff;
print("Running Intensity CutOff Optimization!" + " Value: " + intensityCutOff + " - Sigma value equal to: " + sigma);
print("Running Area CutOff Optimization!" + " Value: " + areaCutOff);
// Do not include NaN for the intensity and area cutoff calculation
if (!isNaN(intensityCutOff) || !isNaN(areaCutOff)) {
optIntArray[i] = intensityCutOff;
optAreaArray[i] = areaCutOff;
} else {
reduceNaN += 1;
print("Reducing count: " + reduceNaN);
}
} else {
for (l = 0; l < optIntSteps; l++) {
optValue += optIntArray[l];
optArea += optAreaArray[l];
}