-
Notifications
You must be signed in to change notification settings - Fork 1
/
OrgQ_simple.py
480 lines (334 loc) · 14.3 KB
/
OrgQ_simple.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
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
#
# OrgQ - ImageJ Macro written in Python
#
# Input - Folders containing split channel images for Organoids
# - The filenames of the images must end in ch00, ch01, ch02, ch03
# - Optional thresholding can be loaded as well
# Output - CSV file containing nuclei counts and marker colocalization data for each image
# - Intensity per area
# - Count number of pixels for each marker
# Written by: Eddie Cai & Rhalena A. Thomas
# Incorporating analysis ideas from Vincent Soubanier and Valoria
import os, sys, math, csv, datetime
from ij import IJ, Prefs, ImagePlus
from ij.io import DirectoryChooser
from ij.io import OpenDialog
from ij.measure import ResultsTable
from ij.measure import Measurements
from ij.process import ImageProcessor
from ij.process import ImageConverter
from ij.plugin.frame import RoiManager
from ij.plugin.filter import ParticleAnalyzer
from ij.gui import GenericDialog
from ij.gui import WaitForUserDialog
from ij.plugin.filter import ThresholdToSelection
from ij.WindowManager import getImage
from ij.WindowManager import setTempCurrentImage
# To enable displayImages mode (such as for testing thresholds), make displayImages = True
displayImages = True
# Function to get the markers needed with a generic dialog for each subfolder, as well as the name of the output for that subfolder
def getChannels(subFolder):
gd = GenericDialog("Channel Options")
gd.addMessage("Name the markers associated with this directory:")
gd.addMessage(inputDirectory + subFolder)
gd.addMessage("(Leave empty to ignore)")
gd.addMessage("")
gd.addStringField("Channel ch00:", "Dapi")
gd.addStringField("Channel ch01:", "pSYN")
gd.addStringField("Channel ch02:", "MAP2")
gd.addStringField("Channel ch03:", "SYN")
gd.addMessage("")
gd.addStringField("What would you like the output file to be named:", "output")
gd.showDialog()
channelNames = []
channelNames.append([gd.getNextString(), 0])
channelNames.append([gd.getNextString(), 1])
channelNames.append([gd.getNextString(), 2])
channelNames.append([gd.getNextString(), 3])
outputName = gd.getNextString()
channels = []
for i,v in enumerate(channelNames):
if v[0] != "":
channels.append(v)
if gd.wasCanceled():
print "User canceled dialog!"
return
return channels, outputName
# Function to get the thresholds.
def getThresholds():
thresholds = {}
gd = GenericDialog("Threshold options")
gd.addChoice("How would you like to set your thresholds?", ["default", "use threshold csv file"], "default")
gd.showDialog()
choice = gd.getNextChoice()
log.write("Option: " + choice + "\n")
if choice == "use threshold csv file":
path = OpenDialog("Open the thresholds csv file")
log.write("File used: " + path.getPath() + "\n")
with open(path.getPath()) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
thresholds = row
return thresholds
def rreplace(s, old, new):
return (s[::-1].replace(old[::-1],new[::-1], 1))[::-1]
############# Main loop, will run for every image. ##############
def process(subFolder, outputDirectory, filename):
imp = IJ.openImage(inputDirectory + subFolder + '/' + rreplace(filename,"_ch00.tif",".tif"))
IJ.run(imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001")
ic = ImageConverter(imp);
ic.convertToGray8();
IJ.setThreshold(imp, 2, 255)
IJ.run(imp, "Convert to Mask", "")
IJ.run(imp, "Remove Outliers...", "radius=5" + " threshold=50" + " which=Dark")
IJ.run(imp, "Remove Outliers...", "radius=5" + " threshold=50" + " which=Bright")
imp.getProcessor().invert()
rm = RoiManager(True)
imp.getProcessor().setThreshold(0, 0, ImageProcessor.NO_LUT_UPDATE)
boundroi = ThresholdToSelection.run(imp)
rm.addRoi(boundroi)
if not displayImages:
imp.changes = False
imp.close()
images = [None] * 5
intensities = [None] * 5
blobsarea = [None] * 5
blobsnuclei = [None] * 5
bigAreas = [None] * 5
for chan in channels:
v, x = chan
images[x] = IJ.openImage(inputDirectory + subFolder + '/' + rreplace(filename,"_ch00.tif","_ch0"+str(x)+".tif"))
imp = images[x]
for roi in rm.getRoisAsArray():
imp.setRoi(roi)
stats = imp.getStatistics(Measurements.MEAN | Measurements.AREA)
intensities[x] = stats.mean
bigAreas[x] = stats.area
rm.close()
# Opens the ch00 image and sets default properties
imp = IJ.openImage(inputDirectory + subFolder + '/' + filename)
IJ.run(imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001")
# Sets the threshold and watersheds. for more details on image processing, see https://imagej.nih.gov/ij/developer/api/ij/process/ImageProcessor.html
ic = ImageConverter(imp);
ic.convertToGray8();
IJ.run(imp, "Remove Outliers...", "radius=2" + " threshold=50" + " which=Dark")
IJ.run(imp,"Gaussian Blur...","sigma="+str(blur))
IJ.setThreshold(imp, lowerBounds[0], 255)
if displayImages:
imp.show()
IJ.run(imp, "Convert to Mask", "")
IJ.run(imp, "Watershed", "")
if not displayImages:
imp.changes = False
imp.close()
# Counts and measures the area of particles and adds them to a table called areas. Also adds them to the ROI manager
table = ResultsTable()
roim = RoiManager(True)
ParticleAnalyzer.setRoiManager(roim);
pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA, table, 15, 9999999999999999, 0.2, 1.0)
pa.setHideOutputImage(True)
#imp = impM
# imp.getProcessor().invert()
pa.analyze(imp)
areas = table.getColumn(0)
# This loop goes through the remaining channels for the other markers, by replacing the ch00 at the end with its corresponding channel
# It will save all the area fractions into a 2d array called areaFractionsArray
areaFractionsArray = [None] * 5
for chan in channels:
v, x = chan
# Opens each image and thresholds
imp = images[x]
IJ.run(imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001")
ic = ImageConverter(imp);
ic.convertToGray8();
IJ.setThreshold(imp, lowerBounds[x], 255)
if displayImages:
imp.show()
WaitForUserDialog("Title", "Adjust Threshold for Marker " + v).show()
IJ.run(imp, "Convert to Mask", "")
# Measures the area fraction of the new image for each ROI from the ROI manager.
areaFractions = []
for roi in roim.getRoisAsArray():
imp.setRoi(roi)
stats = imp.getStatistics(Measurements.AREA_FRACTION)
areaFractions.append(stats.areaFraction)
# Saves the results in areaFractionArray
areaFractionsArray[x] = areaFractions
roim.close()
for chan in channels:
v, x = chan
imp = images[x]
imp.deleteRoi()
roim = RoiManager(True)
ParticleAnalyzer.setRoiManager(roim);
pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA, table, 15, 9999999999999999, 0.2, 1.0)
pa.analyze(imp)
blobs = []
for roi in roim.getRoisAsArray():
imp.setRoi(roi)
stats = imp.getStatistics(Measurements.AREA)
blobs.append(stats.area)
blobsarea[x] = sum(blobs)
blobsnuclei[x] = len(blobs)
if not displayImages:
imp.changes = False
imp.close()
roim.reset()
roim.close()
# Creates the summary dictionary which will correspond to a single row in the output csv, with each key being a column
summary = {}
summary['Image'] = filename
summary['Directory'] = subFolder
# Adds usual columns
summary['size-average'] = 0
summary['#nuclei'] = 0
summary['all-negative'] = 0
summary['too-big-(>'+str(tooBigThreshold)+')'] = 0
summary['too-small-(<'+str(tooSmallThreshold)+')'] = 0
# Creates the fieldnames variable needed to create the csv file at the end.
fieldnames = ['Name','Directory', 'Image', 'size-average', 'too-big-(>'+str(tooBigThreshold)+')','too-small-(<'+str(tooSmallThreshold)+')', '#nuclei', 'all-negative']
# Adds the columns for each individual marker (ignoring Dapi since it was used to count nuclei)
summary["organoid-area"] = bigAreas[x]
fieldnames.append("organoid-area")
for chan in channels:
v, x = chan
summary[v+"-positive"] = 0
fieldnames.append(v+"-positive")
summary[v+"-intensity"] = intensities[x]
fieldnames.append(v+"-intensity")
summary[v+"-blobsarea"] = blobsarea[x]
fieldnames.append(v+"-blobsarea")
summary[v+"-blobsnuclei"] = blobsnuclei[x]
fieldnames.append(v+"-blobsnuclei")
# Adds the column for colocalization between first and second marker
if len(channels) > 2:
summary[channels[1][0]+'-'+channels[2][0]+'-positive'] = 0
fieldnames.append(channels[1][0]+'-'+channels[2][0]+'-positive')
# Adds the columns for colocalization between all three markers
if len(channels) > 3:
summary[channels[1][0]+'-'+channels[3][0]+'-positive'] = 0
summary[channels[2][0]+'-'+channels[3][0]+'-positive'] = 0
summary[channels[1][0]+'-'+channels[2][0]+'-' +channels[3][0]+ '-positive'] = 0
fieldnames.append(channels[1][0]+'-'+channels[3][0]+'-positive')
fieldnames.append(channels[2][0]+'-'+channels[3][0]+'-positive')
fieldnames.append(channels[1][0]+'-'+channels[2][0]+'-' +channels[3][0]+ '-positive')
# Loops through each particle and adds it to each field that it is True for.
areaCounter = 0
for z, area in enumerate(areas):
log.write(str(area))
log.write("\n")
if area > tooBigThreshold:
summary['too-big-(>'+str(tooBigThreshold)+')'] += 1
elif area < tooSmallThreshold:
summary['too-small-(<'+str(tooSmallThreshold)+')'] += 1
else:
summary['#nuclei'] += 1
areaCounter += area
temp = 0
for chan in channels:
v, x = chan
if areaFractionsArray[x][z] > areaFractionThreshold[0]: #theres an error here im not sure why. i remember fixing it before
summary[chan[0]+'-positive'] += 1
if x != 0:
temp += 1
if temp == 0:
summary['all-negative'] += 1
if len(channels) > 2:
if areaFractionsArray[1][z] > areaFractionThreshold[1]:
if areaFractionsArray[2][z] > areaFractionThreshold[2]:
summary[channels[1][0]+'-'+channels[2][0]+'-positive'] += 1
if len(channels) > 3:
if areaFractionsArray[1][z] > areaFractionThreshold[1]:
if areaFractionsArray[3][z] > areaFractionThreshold[3]:
summary[channels[1][0]+'-'+channels[3][0]+'-positive'] += 1
if areaFractionsArray[2][z] > areaFractionThreshold[2]:
if areaFractionsArray[3][z] > areaFractionThreshold[3]:
summary[channels[2][0]+'-'+channels[3][0]+'-positive'] += 1
if areaFractionsArray[1][z] > areaFractionThreshold[1]:
summary[channels[1][0]+'-'+channels[2][0]+'-' +channels[3][0]+ '-positive'] += 1
# Calculate the average of the particles sizes
if float(summary['#nuclei']) > 0:
summary['size-average'] = round( areaCounter / summary['#nuclei'], 2)
# Opens and appends one line on the final csv file for the subfolder (remember that this is still inside the loop that goes through each image)
with open(outputDirectory + "/" + outputName +".csv", 'a') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames, extrasaction='ignore', lineterminator = '\n')
if os.path.getsize(outputDirectory + "/" + outputName +".csv") < 1:
writer.writeheader()
writer.writerow(summary)
########################## code begins running here ##############################
# Get input and output directories
dc = DirectoryChooser("Choose an input directory")
inputDirectory = dc.getDirectory()
dc = DirectoryChooser("Choose an output directory")
outputDirectory = dc.getDirectory()
# Opens log file
with open(outputDirectory + "log.txt", "w") as log:
log.write("log: "+datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
log.write("\n")
log.write("________________________\n")
log.write("Input directory selected: " + inputDirectory + "\n")
log.write("________________________\n")
log.write("Output directory selected: " + outputDirectory + "\n")
# Finds all the subfolders in the main directory
directories = []
for subFolder in os.listdir(inputDirectory):
if os.path.isdir(inputDirectory + subFolder):
directories.append(subFolder)
print("subfolder found")
# A few default options
areaFractionThreshold = [0.1, 0.1, 0.1, 0.1, 0.1] #you can change these
tooSmallThreshold = 50
tooBigThreshold = 500
blur = 1
log.write("________________________\n")
log.write("Default calculation thresholds: \n")
log.write(" areaFractionThreshold:" + str(areaFractionThreshold) + "\n")
log.write(" tooSmallThreshold:" + str(tooSmallThreshold)+"\n")
log.write(" tooBigThreshold:" + str(tooBigThreshold)+"\n")
# Get options from user. (see functions written on top)
log.write("________________________\n")
log.write("Getting thresholds...\n")
thresholds = getThresholds()
# Set arrays to store data for each subfolder
allChannels = []
allOutputNames = []
for subFolder in directories:
chan, outputName = getChannels(subFolder)
allChannels.append(chan)
allOutputNames.append(outputName)
# Loop that goes through each sub folder.
log.write("_______________________________________________________________________\n")
log.write("Beginning main directory loop: \n")
log.write("\n")
for inde, subFolder in enumerate(directories):
log.write("______________________________________\n")
log.write("Subfolder: "+ subFolder +"\n")
log.write("\n")
channels = allChannels[inde]
outputName = allOutputNames[inde]
log.write("Channels: "+ str(channels) +"\n")
log.write("Output Name: "+ outputName +"\n")
open(outputDirectory + "/" + outputName +".csv", 'w').close
lowerBounds = [40, 20, 35, 50, 40]
for chan in channels:
v, x = chan
if v in thresholds:
lowerBounds[x] = int(thresholds[v])
log.write("Lower Bound Thresholds: "+ str(lowerBounds) +"\n")
# Finds all correct EVOS split channel ch0 files and runs through them one at a time (see main loop process() on top)
log.write("_________________________\n")
log.write("Begining loop for each image \n")
for filename in os.listdir(inputDirectory + subFolder):
if filename.endswith("ch00.tif"):
log.write("Processing: " + filename +" \n")
process(subFolder, outputDirectory, filename);
log.write("_________________________\n")
log.write("Completed subfolder " + subFolder + ". \n")
log.write("\n")
cat = """
\ /\ Macro completed!
) ( ') meow!
( / )
\(__)|"""
log.write(cat)
print(cat)