from ij import IJ, ImagePlus
from loci.plugins import BF
from ij.measure import ResultsTable
from ij.plugin.frame import RoiManager
import ij
from ij.gui import ShapeRoi
import csv
#IJ.run("Open...")
array = {"File Name": [], "Mean Cell Size": [], "Cell Count":[], "Area":[]}
continuing = True
while True:
	a = IJ.getImage()
	f1 = a.title
	directory = a.getOriginalFileInfo().directory
	IJ.run("Split Channels")
	IJ.selectWindow(f1+' (blue)')
	IJ.run("Close")
	IJ.selectWindow(f1+' (green)')
	IJ.run("Close")
	IJ.selectWindow(f1+' (red)')
	IJ.run("8-bit")
	
	
	#HEre is code for normal thresholding
	
	IJ.setMinAndMax(50, 255)
	IJ.setThreshold(50, 255)
	IJ.run("Convert to Mask")
	IJ.run("Analyze Particles...", "size=51-550000 show=Outlines display include summarize record add")
	joinkies = IJ.getImage()
	joinkies.close()
	gg = IJ.getImage()
	gg.close()
	IJ.selectWindow("Summary")
	summary = ResultsTable.getResultsTable()
	IJ.renameResults("Results")
	summary = ResultsTable.getResultsTable()
	array['Area'].append(float(summary.getColumn(summary.getColumnIndex("Total Area"))[-1]))
	IJ.open(directory+f1)
	IJ.selectWindow(f1)
	IJ.run("Split Channels")
	IJ.selectWindow(f1 + ' (green)')
	IJ.run("Close")
	IJ.run("Clear Results")
	
	IJ.selectWindow(f1+' (blue)')
	blue_channel = IJ.getImage()
	rm = RoiManager().getInstance()
	rois = rm.getRoisAsArray()
	shape_united = None
	roi1 = None
	if len(rois)>1:
		for roi in rois:
			if roi1:
				if shape_united:
					roi2 = ShapeRoi(roi)
					shape_united = shape_united.or(roi2)
				else:
					roi2 = ShapeRoi(roi)
					shape_united = roi1.or(roi2)	
			else:
				roi1 = ShapeRoi(roi)
	else:
		blue_channel.setRoi(rois[0])
	#IJ.run("Colocalization Threshold", "channel_1=["+f1+" (red)"+"] channel_2=["+f1+" (blue)"+"] use=[Channel 2] channel=[Red : Blue] show use_0 show_0 include")
	IJ.selectWindow(f1+' (blue)')
	IJ.run("Clear Outside")
	IJ.run("Gaussian Blur...", "sigma=1 scaled")
	IJ.run("Find Maxima...", "prominence=10 strict output=[Count]")
	res = ResultsTable.getResultsTable()
	
	array['Cell Count'].append(float(res.getColumn(res.getColumnIndex("Count"))[-1]))
	array['File Name'].append(str(f1))
	
	array["Mean Cell Size"].append(array["Area"][-1]/array["Cell Count"][-1])
	
	IJ.selectWindow("ROI Manager")
	IJ.run("Close")
	IJ.selectWindow("Results")
	IJ.run("Close")
	IJ.selectWindow(f1+' (blue)')
	IJ.run("Close")
	IJ.selectWindow(f1+' (red)')
	IJ.run("Close")
	try:
		a = IJ.getImage()
	except:
		break
with open(directory+'Cell Sizes.csv', 'wb') as output:
	writer = csv.writer(output)
	writer.writerow(['File Name', "Mean Cell Size", "Area", "Cell Count"])
	for i in range(len(array['File Name'])):
		writer.writerow([array['File Name'][i], array["Mean Cell Size"][i], array["Area"][i], array["Cell Count"][i]])
		 
