/*
 * Calculating Magnitude and Phase from the IJ complex FFT
 * Jean-Christophe Taveau
 * 2022/07/20
 */
 
const imp = IJ.getImage();
IJ.run("FFT Options...", "fft complex");
IJ.run(imp, "FFT", "");
const power = FFT.forward(imp);
//IJ.run("Swap Quadrants", "");
const fft = IJ.getImage();
const w = fft.getWidth();
const h = fft.getHeight();
print(fft.getNSlices());
print(w + h);

// Create Output
const mag = new FloatProcessor(w,h);
const phase = new FloatProcessor(w,h);

// Calc Magnitude and Phase
const re = fft.getImageStack().getProcessor(1);
const im = fft.getImageStack().getProcessor(2);
for (let i = 0; i < w*h;i++) {
  const magi = Math.sqrt(re.getf(i)*re.getf(i) + im.getf(i)*im.getf(i) );
  const phasei = Math.atan2(im.getf(i), re.getf(i) );
  mag.setf(i,magi);
  phase.setf(i,phasei);
}

const stack = new ImageStack();
stack.addSlice(mag);
stack.addSlice(phase);
const output = new ImagePlus("Magnitude and Phase",stack);
output.show();