/
InvasionCounter.py
240 lines (203 loc) · 9.59 KB
/
InvasionCounter.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
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
import ij.IJ as IJ
import ij.ImagePlus as ImagePlus
# import ij.ImageStack as ImageStack
# import ij.WindowManager as wm
import ij.measure.ResultsTable as ResultsTable
import ij.measure.Measurements as Measurements
import ij.plugin.ChannelSplitter as ChannelSplitter
import ij.plugin.HyperStackConverter as HyperStackConverter
import ij.plugin.ZProjector as ZProjector
# import ij.plugin.RGBStackMerge as RGBStackMerge
# import ij.plugin.StackCombiner as StackCombiner
# import ij.plugin.MontageMaker as MontageMaker
# import ij.plugin.StackCombiner as StackCombiner
# import ij.plugin.Duplicator as Duplicator
# import ij.plugin.Concatenator as Concatenator
# import ij.plugin.Thresholder as Thresholder
import ij.plugin.filter.ParticleAnalyzer as ParticleAnalyzer
# import ij.plugin.filter.BackgroundSubtracter as BackgroundSubtracter
# import ij.plugin.filter.EDM as EDM
import os
import math
def readdirfiles(directory):
"""Import tiff files from a directory.
This function reads all .tiff files from a directory and it's subdirectories and returns them as a list of
hyperstacks.
Args:
directory: The path to a directory containing the tiff files.
Returns:
A list of filepaths.
"""
# Get the list of all files in directory tree at given path
listOfFiles = list()
for (dirpath, dirnames, filenames) in os.walk(directory):
listOfFiles += [os.path.join(dirpath, file) for file in filenames]
return listOfFiles
def saveresults(dir, name):
outfile = os.path.join(dir, "{}.csv".format(name))
res = ResultsTable.getResultsTable()
ResultsTable.save(res, outfile)
ResultsTable.reset(res)
def stackprocessor(path, nChannels=4, nSlices=1, nFrames=1):
imp = ImagePlus(path)
imp = HyperStackConverter().toHyperStack(imp,
nChannels, # channels
nSlices, # slices
nFrames) # frames
imp = ZProjector.run(imp, "max")
return imp
def countobjects(imp, rt,
subtractBackground=False, watershed=False, dilate=False,
threshMethod="Otsu", physicalUnits=True,
minSize=0.00, maxSize=float("inf"),
minCirc=0.00, maxCirc=1.00):
"""Threshold and count objects in channel 'channelNumber'.
This function splits an image in the separate channels, and counts the number of objects in the thresholded
channel.
Args:
imp: An ImagePlus with 1 frame, 1 slice.
Returns:
A list of filepaths.
"""
cal = imp.getCalibration()
if subtractBackground:
IJ.run(imp, "Subtract Background...", "rolling=50")
IJ.setAutoThreshold(imp, "{} dark".format(threshMethod))
IJ.run(imp, "Convert to Mask", "")
if dilate:
IJ.run(imp, "Dilate", "")
if watershed:
IJ.run(imp, "Watershed", "")
if physicalUnits: # Convert physical units to pixels for the current calibration.
minSize = cal.getRawX(math.sqrt(minSize)) ** 2
maxSize = cal.getRawX(math.sqrt(maxSize)) ** 2
pa = ParticleAnalyzer(
ParticleAnalyzer.SHOW_OVERLAY_OUTLINES|ParticleAnalyzer.DISPLAY_SUMMARY, #int options
Measurements.AREA|Measurements.SHAPE_DESCRIPTORS|Measurements.MEAN|Measurements.CENTROID|Measurements.LABELS, #int measurements
rt, #ResultsTable
minSize, #double
maxSize, #double
minCirc, #double
maxCirc) #double
pa.analyze(imp)
return imp
def main():
# Prepare directory tree for output.
indir = IJ.getDirectory("input directory")
outdir = IJ.getDirectory(".csv output directory")
nucdir = os.path.join(outdir, "nuclei")
bacdir = os.path.join(outdir, "bacteria")
rufdir = os.path.join(outdir, "ruffles")
gfpdir = os.path.join(outdir, "gfp")
channelsdir = os.path.join(outdir, "channels")
if not os.path.isdir(nucdir):
os.mkdir(nucdir)
if not os.path.isdir(bacdir):
os.mkdir(bacdir)
if not os.path.isdir(rufdir):
os.mkdir(rufdir)
if not os.path.isdir(gfpdir):
os.mkdir(gfpdir)
if not os.path.isdir(channelsdir):
os.mkdir(channelsdir)
# Collect all file paths in the input directory
files = readdirfiles(indir)
nucResults = ResultsTable()
bacResults = ResultsTable()
rufResults = ResultsTable()
gfpResults = ResultsTable()
for file in files:
if file.endswith('ome.tif') or file.endswith('ome.tiff'):
imp = stackprocessor(file,
nChannels=4,
nSlices=7,
nFrames=1)
channels = ChannelSplitter.split(imp)
name = imp.getTitle()
IJ.log("Processing image: {}".format(name))
for c in range(len(channels)):
IJ.run(channels[c], "Grays", "")
IJ.run(channels[c], "Invert", "")
jpgname = channels[c].getShortTitle()
jpgoutfile = os.path.join(channelsdir, "{}.jpg".format(jpgname))
IJ.saveAs(channels[c].flatten(), "Jpeg", jpgoutfile)
IJ.run(channels[c], "Invert", "")
nuc = countobjects(channels[0], nucResults,
threshMethod="Triangle",
subtractBackground=True,
# dilate=True,
watershed=True,
minSize=3.00,
maxSize=100,
minCirc=0.00,
maxCirc=1.00)
bac = countobjects(channels[1], bacResults,
threshMethod="RenyiEntropy",
subtractBackground=False,
watershed=False,
minSize=0.20,
maxSize=30.00,
minCirc=0.00,
maxCirc=1.00)
ruf = countobjects(channels[2], rufResults,
threshMethod="RenyiEntropy",
minSize=2.00,
maxSize=30.00,
minCirc=0.20,
maxCirc=1.00)
gfp = countobjects(channels[3], gfpResults,
threshMethod="RenyiEntropy",
subtractBackground=False,
watershed=True,
minSize=0.20,
maxSize=30.00,
minCirc=0.00,
maxCirc=1.00)
# binaries = [nuc, bac, ruf, gfp]
# channels[0].show()
# binaries[0].show()
# binMontage = RGBStackMerge().mergeChannels(binaries, False)
# binMontage.show()
# chsMontage = RGBStackMerge().mergeChannels(channels, False)
# binMontage = MontageMaker().makeMontage2(binMontage,
# 4, # int columns
# 4, # int rows
# 1.00, # double scale
# 1, # int first
# 16, # int last
# 1, # int inc
# 0, # int borderWidth
# False) # boolean labels)
# chsMontage = MontageMaker().makeMontage2(chsMontage,
# 4, # int columns
# 4, # int rows
# 1.00, # double scale
# 1, # int first
# 16, # int last
# 1, # int inc
# 0, # int borderWidth
# False) # boolean labels)
#
# binMontage.show()
# chsMontage.show()
outfilenuc = os.path.join(nucdir, "threshold_nuc_{}".format(name))
outfilebac = os.path.join(bacdir, "threshold_bac_{}".format(name))
outfileruf = os.path.join(rufdir, "threshold_ruf_{}".format(name))
outfilegfp = os.path.join(gfpdir, "threshold_gfp_{}".format(name))
IJ.saveAs(nuc.flatten(), "Tiff", outfilenuc)
IJ.saveAs(bac.flatten(), "Tiff", outfilebac)
IJ.saveAs(ruf.flatten(), "Tiff", outfileruf)
IJ.saveAs(gfp.flatten(), "Tiff", outfilegfp)
nucResults.show("nuclei")
bacResults.show("bacteria")
rufResults.show("ruffles")
gfpResults.show("gfp")
nucout = os.path.join(outdir, "nuclei.csv")
bacout = os.path.join(outdir, "bacteria.csv")
rufout = os.path.join(outdir, "ruffles.csv")
gfpout = os.path.join(outdir, "gfp.csv")
ResultsTable.save(nucResults, nucout)
ResultsTable.save(bacResults, bacout)
ResultsTable.save(rufResults, rufout)
ResultsTable.save(gfpResults, gfpout)
main()