ImageJ Macro To Divide Stack to Multiple Patches

Hi guys,

I am currently encountering an issue on dividing a stack into multiple patches. For example, I have 1000 slices, and I want to divide it into 4x4 patches. I want the result to be the following:
Stack 1: Left-most 4x4 of slice 1, Left-most 4x4 of slice 2, … , Left-most of slice 1000
Stack 2: Next 4x4 of slice 1, and so on
And I would like to save each stack as separate files.

This is the code that I have been developing:

n = getNumber("How many divisions?", 2); 
id = getImageID(); 

path = getDirectory("image");
title = getTitle(); 
getLocationAndSize(locX, locY, sizeW, sizeH); 
width = getWidth(); 
height = getHeight(); 
tileWidth = width / n; 
tileHeight = height / n;
depth = nSlices;
name = 0;
 
for (y = 0; y < 1; y++) { 
    offsetY = y * height / n; 
    for (x = 0; x < 1; x++) { 
        offsetX = x * width / n;  
        newImage(name, "16-bit", tileWidth, tileHeight, depth);
        for (i = 1; i <= nSlices; i++) {
            Stack.setSlice(i);
            selectImage(id);
            call("ij.gui.ImageWindow.setNextLocation", locX + offsetX, locY + offsetY); 
            makeRectangle(offsetX, offsetY, tileWidth, tileHeight); 
            run("Crop");
        }         
       saveAs("tiff",path+tileTitle);
    } 
    name++;
} 

selectImage(id); 
close();

But I confused on how to create a new stack, then take the cropped from the slice of the original stack, put it to the new stack, and go on to the next slice.

Hi @mario7lorenzo,

if I understand correctly what you try to do the simplest solution is to skip the for loop running through slices and just create the rectangle. After that instead of cropping use the command run("Duplicate");. This way it automatically gives you the part you selected as a copy of the complete stack (if you activate to copy the complete stack in the duplication dialog while recording).

This macro (adapted from yours) shows that:

run("T1 Head (16-bits)");
n = getNumber("How many divisions?", 2); 
id = getImageID(); 

path = getDirectory("image");
title = getTitle(); 
getLocationAndSize(locX, locY, sizeW, sizeH); 
width = getWidth(); 
height = getHeight(); 
tileWidth = width / n; 
tileHeight = height / n;
depth = nSlices;
name = 0;

for (y = 0; y < n; y++) { 
    offsetY = y * height / n; 
    for (x = 0; x < n; x++) { 
        offsetX = x * width / n;  
		selectImage(id);
		makeRectangle(offsetX, offsetY, tileWidth, tileHeight); 
		call("ij.gui.ImageWindow.setNextLocation", locX + offsetX, locY + offsetY); 
		run("Duplicate...", "duplicate");
	}
}

Hi, @biovoxxel !

It works, I have not familiarized myself with macro programming hahah. Thank you so much for your help!