-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfluo_count.py
143 lines (111 loc) · 5.15 KB
/
fluo_count.py
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
# Copyright 2017, Anthony Westbrook <[email protected]>, University of New Hampshire
# To install this script as a FIJI macro, perform the following steps:
#
# 1. From the "Plugins" menu, select "Install..."
# 2. Select this script (fluo_count.py)
# 3. Accept the default installation directory
# 4. Restart FIJI
# 5. The plugin will be available to run from the "Plugins" menu at the bottom
from ij import IJ, WindowManager
from ij.measure import ResultsTable
from fiji.util.gui import GenericDialogPlus
from trainableSegmentation import WekaSegmentation
import math
import sys
import os
HEADER = "File\tProbability\tCell\tArea\tPerimeter\tCircularity\tAspectRatio\tRoundness\tSolidity"
RESULTS_FILE = "results.csv"
def setupMeasurements():
options = "area perimeter shape roundness"
IJ.run("Set Measurements...", options)
def optionsDialog():
dialog = GenericDialogPlus("Fluorescent Cell Counting")
dialog.addDirectoryField("Image Directory", "")
dialog.addFileField("Training Model", "")
dialog.addStringField("Output Subdirectory", "output", 20)
dialog.addStringField("Probability Threshold", "0.67", 20)
dialog.addStringField("Minimum Pixel Size", "2", 20)
dialog.showDialog()
# Check if canceled
if dialog.wasCanceled(): return None
textVals = [x.text for x in dialog.getStringFields()]
return textVals
def prepareImage(passDir, passFile):
# Attempt to open as image, exit if not
fullPath = os.path.join(passDir, passFile)
retImage = IJ.openImage(fullPath)
if not retImage: return None
retImage.show()
return retImage
def finalizeImage(passImage):
passImage.changes = False
passImage.close()
def analyzeImage(passImage, passModel, passProbability, passPixels, passOutput):
retResults = list()
# Apply WEKA training model to image
wekaSeg = WekaSegmentation(passImage)
wekaSeg.loadClassifier(passModel)
wekaSeg.applyClassifier(True)
# Extract first slice of probability map
wekaImg = wekaSeg.getClassifiedImage();
wekaImg.show()
IJ.selectWindow("Probability maps")
IJ.setSlice(1)
IJ.run("Duplicate...", "title=temp")
# Apply threshold and save
IJ.setThreshold(passProbability, 1, "Black & White")
fileParts = passImage.getTitle().split(".")
IJ.save(os.path.join(passOutput, "{0}-probmap.png".format(fileParts[0], '.'.join(fileParts[1:]))))
# Perform particle analysis and save
IJ.run("Analyze Particles...", "size={0}-Infinity show=Outlines pixel clear".format(passPixels))
IJ.selectWindow("Drawing of temp")
IJ.save(os.path.join(passOutput, "{0}-particles.png".format(fileParts[0], '.'.join(fileParts[1:]))))
# Get measurements (skip final row, this will correspond to legend)
tableResults = ResultsTable.getResultsTable()
for rowIdx in range(tableResults.size() - 1):
retResults.append(tableResults.getRowAsString(rowIdx).split())
# Close interim windows
IJ.run("Close")
IJ.selectWindow("temp")
IJ.run("Close")
IJ.selectWindow("Probability maps")
IJ.run("Close")
return retResults
def processImages(passOptions):
optImageDir = passOptions[0]
optModel = passOptions[1]
optOutput = passOptions[2]
optProbability = 1.0 - float(passOptions[3])
optPixels = int(passOptions[4])
retResults = dict()
# Iterate through all images in chosen directory
root, dirs, files = next(os.walk(optImageDir))
for curFile in files:
# Prepare image
curImage = prepareImage(root, curFile)
if not curImage: continue
# Analyze image
retResults[curFile] = analyzeImage(curImage, optModel, optProbability, optPixels, os.path.join(options[0], optOutput))
# Close image
finalizeImage(curImage)
return retResults
def writeResults(passResults, passOutput, passProbability):
# Create results TSV
with open(passOutput, "w") as fileHandle:
fileHandle.write("{0}\n".format(HEADER))
for image in passResults:
for row in passResults[image]:
fieldText = "\t".join(map(str, row))
fileHandle.write("{0}\t{1}\t{2}\n".format(image, passProbability, fieldText))
# Setup measurements to record in CSV
setupMeasurements()
# Present user definable options, then process
options = optionsDialog()
if options:
# Prepare output directory
if not os.path.exists(os.path.join(options[0], options[2])):
os.makedirs(os.path.join(options[0], options[2]))
# Analyze images
results = processImages(options)
writeResults(results, os.path.join(options[0], options[2], RESULTS_FILE), options[3])
IJ.showMessage("Analysis Complete!")