Macro for hyperstack analysis

I have been trying to make a Fiji macro for image analysis of Leica hyperstacks (lif) over the last few days, but I am not getting anywhere on my own. This is my first Fiji macro, so I am very much a beginner.

Basically I have stacks with two channels and two or more cells in the frame. In the first channel there is a signal which pretty much corresponds to the nuclei. The second channel is the signal I am interested in. The goal is to make a mask of channel 1 for every layer and remove everything around that mask in the same layer of channel 2. So in essence I only get the signal of channel 2 within the nuclei and then make a MIP out of it. So far I recorded what I did for a single slice. There it works great, but I am having trouble automating it on the stack.

  1. I dont know how to best address the stack channels. Should I leave it as a two channel stack or split the channels?

  2. Only channel 1 should be converted to the mask and not both.

  3. In the loop I need to copy the results of a particle analysis to the other channel and remove the outside signal. I have also tried with overlays (Overlay.copy & Overlay.paste), but always get an error message that the overlay clipboard is empty.

Stack.getDimensions(width, height, channels, slices, frames); 

//create binary mask in channel 1
run("Median...", "radius=5 stack");
run("Maximum...", "radius=5 stack");
setAutoThreshold("MaxEntropy dark");
setThreshold(7, 255);
setOption("BlackBackground", true);
run("Convert to Mask", "method=MaxEntropy background=Dark black");
run("Variance...", "radius=6 stack");
run("Fill Holes", "stack");
run("EDM Binary Operations", "iterations=10 operation=close stack");
run("EDM Binary Operations", "iterations=20 operation=open stack");
run("EDM Binary Operations", "iterations=10 operation=erode stack");

//copy mask to channel 2, remove area outside mask -> repeat for whole stack
for (i=1; i<=slices; i++) { 
        run("Analyze Particles...", "size=10000-Infinity pixel show=Overlay exclude slice");
        roiManager("Select", newArray(0,1));
	run("Restore Selection");
	setBackgroundColor(0, 0, 0);
	run("Clear Outside", "slice");

//MIP chanel 2
run("Z Project...", "projection=[Max Intensity]");