/**
 * This script is intended to be used in conjunction with the CameraLabs.bsh
 * script. See https://micro-manager.org/wiki/Measuring_camera_specifications
 * for more information.
 */

import org.jfree.data.xy.XYSeries;
import ij.measure.ResultsTable;


img = ij.IJ.getImage();
ij.ImageStack stack = img.getImageStack();
sqrt2 = Math.sqrt(2);
ij.plugin.ImageCalculator calc = new ij.plugin.ImageCalculator();
XYSeries data = new XYSeries("");
ResultsTable rt = new ResultsTable();
rt.reset();

for (int i=0; i <stack.getSize()/2; i++) {
	ip = stack.getProcessor(2*i + 1);
	ip2 = stack.getProcessor(2*i + 2);
	ij.process.ImageStatistics stats = ip.getStatistics();
	ipDiff = calc.run("Subtract create 32-bit", new ij.ImagePlus("1", ip), new ij.ImagePlus("2",ip2) );
	ij.process.ImageStatistics statsDiff = ipDiff.getStatistics();
	stdDev = statsDiff.stdDev/sqrt2;
	rt.incrementCounter();
	rt.addValue("Signal DN", stats.mean);
	rt.addValue("Noise DN", stdDev);
	rt.addValue("Diff in signal", statsDiff.mean); 
	if (i>0) {
		rt.addValue("Slope of Log", ( (Math.log(stdDev) - Math.log(data.getY(i-1))) / (Math.log(stats.mean) - Math.log(data.getX(i-1)))));
		rt.addValue("PCF", stats.mean/(stdDev*stdDev));
	}
	gui.message("Processing: " + i);
	data.add(stats.mean, stdDev);
}

t = "Photon Transfer Data -" + img.getTitle();
rt.show(t);
plotData("Photon Transfer Curve -" + img.getTitle(), data, "Signal (DN)", "Noise (DN)", 100, 100, true, true);

