Batch naming multiple cropped ROIs


#1

Hi there,

I have automated the cropping of multiple ROIs from one image and have some trouble with saving each cropped ROI with a certain name. Let´s say I have 2 ROIs I have cropped from my image. I want to name and save the 1st crop as imageName+_1, the second crop as imageName+_2. How do I do that?

This is the code I am working with so far. It allows me to crop a ROI of a certain size and then crop another ROI if my do/while function returns true.

> //Set ROI size 
> default_crop_width = 150
> default_crop_height = 150
> 
> //Choose the source directory
> dir=getDirectory("Choose a Directory");
> print(dir);
> list = getFileList(dir);
> 
> //Create and name an output directory
> splitDir = dir + "Cropped"+File.separator;
> print(splitDir);
> File.makeDirectory(splitDir);
> 
> //Batch processing
> for (i=0; i<list.length; i++) {
> print(i + ": " + dir+list[i]);
> 
> //Import file
> run("Bio-Formats Importer", "open=" + dir+list[i] + " color_mode=Grayscale view=Hyperstack stack_order=XYCZT");
> 
> //Get file name infos
> imgName=getTitle();
> baseNameEnd=indexOf(imgName, ".nd2");
> baseName=substring(imgName, 0, baseNameEnd); 
> 
> do{
> 
> //Create selection and crop
> run("Duplicate...", "title=Duplicate duplicate");
> selectWindow("Duplicate");
> run("Specify...", "width="+default_crop_width+" height="+default_crop_height+" x=0 y=0");
> waitForUser("Position ROI");
> run("Crop");
> run("Split Channels");
> selectWindow("C1-Duplicate");
> saveAs("Tiff", splitDir + baseName + "_1.tif");
> close();
> }
>
> while (getBoolean("Is there another ROI?"))
>
> }
> run("Close All");
> }

Thanks for any help!

Seb


#2

Hi Seb,

What about using a variable for your ROI#?

Right before your do{} (but within the batch loop) insert:

j=1;

And then within the loop:


do{
 
//...
// [select, split channels, crop stuff goes here]
// ...

saveAs("Tiff", splitDir + baseName + "_"+j+".tif");
j++;

 close();
}

More info: http://imagej.net/Introduction_into_Macro_Programming#Self-referencing_assignments

Hope this helps.


#3

Hi @tswayne,

This is exactly what I needed! Thank you so much!