Drop and Drag. vs, Macro open

Hi, I am writing a macro that seems to be behaving differently than manually opening files. If I use the drag and drop method of opening a file my .tif Images opens with no problem. In my macro I am using the following code. After having preformed Process 1 on Images in directory 1.

getFileList(dir2);
run(“RGB Color”);

I get the following error

“file s not in a supported format a reader plugin is not available or was not found.”

File name1.tif

I have run my updater and ImageJ is up to date.

Does anyone have any ideas?

Welcome to the forum, @susan-sheehan!

Can you post your full macro? The code snippet you posted does not open any images. Are you using the Macro Recorder to generate your macro text?

Have you read the Batch Processing guide?

I used the Macro reader as a guide to start this code, I did read the Batch processing guide, but I cannot find help on this part, its a little complicated, as I am trying to open files from Directory 1 process them, and save Rois from them, then switch directories (I think where I am going wrong) process Images in method 2 then get the roi’s from process 1 to make a measurement on files from process 2. Here is the code as I have it now,

// Macro code for batch processing a folder
// of .tif files, includes saving .tifs back into the 
// ORIGINAL folder with a modified version 
// of the original image name

 dir = getDirectory("Choose input segment Directory ");      // prompts the user to select the folder to be processed, stores the folder as the destination for saving
     list = getFileList(dir);                                             // gives ImageJ a list of all files in the folder to work through
   print(list.length);                                                      // optional prints the number of files in the folder
   dir2 = getDirectory("Choose input Image Directory "); // promts user to select folder to be saved in
    list = getFileList(dir2);
   dir3= getDirectory("Choose output Directory"); //promts user to select folder on Images for Anlaysis 

// Note that the above processes are outside the loop brackets {  }, so they will only be called once at the beginning of the macro


 setBatchMode(false);               // runs up to 6 times faster, without showing images onscreen.  Turn off during troubleshooting steps??
    for (f=0; f<list.length; f++) {    // main files loop (process every image until you get to the bottom of the list), { means open a loop
        path = dir+list[f];                       // creates the filepath for saving
print(path);                                      // optional prints the filepath name to a log window
        showProgress(f, list.length);     // optional progress monitor
        if (!endsWith(path,"/")) open(path);  // open the filepath
if (nImages>=1) {                                          // stop when there are no more images in the folder
// Not needed if folder is only tif  if (endsWith(path,"f")) {        // Processes only tif files.   Useful if there are log or metadata files in the folder  

   start = getTime();                             //optional get start time to see how long a process will take.  Goes with last line print time


   t=getTitle();    // gets the name of the image being processed   
                                     

run("Enhance Contrast...", "saturated=1 normalize");
setAutoThreshold("Default");   //run("Threshold...");
setThreshold(130,255);
setOption("BlackBackground", false);
run("Convert to Mask");
run("Median...", "radius=10");
run("Make Binary");
run("Analyze Particles...", "size=4000-Infinity circularity=0.00-1.00 show=Outlines display include summarize add");
n=roiManager("count");
print("ROI_number=" + n); 
for (i=0; i<n; i++) {
    roiManager("Select", i);
roiManager("Save", dir3 + t + i +".zip")   


path= dir2+list[f];
run("RGB Color");
run("RGB Color");
run("HSB Stack");
run("Stack to Images");
selectWindow("Saturation");
rename(t+ "Saturation");
setThreshold(80, 255);
roiManager("open",dir3 + t + i +".zip");
roiManager("Select", i);
run("Measure");

                              
       }                                 // Closes a loop.  Note there are as many } as there are { in the code, and each } is on it's own line
    }
    }

selectWindow("Results");
saveAs(dir3+"GlomareaandMME.txt");

Great, thanks for posting the macro!

Due to the inconsistent indentation, I had trouble reading it, so I cleaned it up a bit:

// Macro code for batch processing a folder
// of .tif files, includes saving .tifs back into the 
// ORIGINAL folder with a modified version 
// of the original image name

dir = getDirectory("Choose input segment Directory ");     // prompts the user to select the folder to be processed, stores the folder as the destination for saving
list = getFileList(dir);                                   // gives ImageJ a list of all files in the folder to work through
print(list.length);                                        // optional prints the number of files in the folder
dir2 = getDirectory("Choose input Image Directory ");      // promts user to select folder to be saved in
list = getFileList(dir2);
dir3= getDirectory("Choose output Directory");             //promts user to select folder on Images for Anlaysis 

// Note that the above processes are outside the loop brackets {  }, so they will only be called once at the beginning of the macro

setBatchMode(false);                       // runs up to 6 times faster, without showing images onscreen.  Turn off during troubleshooting steps??
for (f=0; f<list.length; f++) {            // main files loop (process every image until you get to the bottom of the list)
  path = dir+list[f];                      // creates the filepath for saving
  print(path);                             // optional prints the filepath name to a log window
  showProgress(f, list.length);            // optional progress monitor
  if (!endsWith(path,"/")) open(path);     // open the filepath
  if (nImages>=1) {                        // stop when there are no more images in the folder
    start = getTime();                     // optional get start time to see how long a process will take.  Goes with last line print time

    t=getTitle();                          // gets the name of the image being processed   

    run("Enhance Contrast...", "saturated=1 normalize");
    setAutoThreshold("Default");
    setThreshold(130,255);
    setOption("BlackBackground", false);
    run("Convert to Mask");
    run("Median...", "radius=10");
    run("Make Binary");
    run("Analyze Particles...", "size=4000-Infinity circularity=0.00-1.00 show=Outlines display include summarize add");
    n=roiManager("count");
    print("ROI_number=" + n); 
    for (i=0; i<n; i++) {
      roiManager("Select", i);
      roiManager("Save", dir3 + t + i +".zip");
      path= dir2+list[f];
      run("RGB Color");
      run("RGB Color");
      run("HSB Stack");
      run("Stack to Images");
      selectWindow("Saturation");
      rename(t+ "Saturation");
      setThreshold(80, 255);
      roiManager("open",dir3 + t + i +".zip");
      roiManager("Select", i);
      run("Measure");
    }
  }
}

selectWindow("Results");
saveAs(dir3+"GlomareaandMME.txt");

Some quick comments:

  • You list the files in dir by writing:

    list = getFileList(dir);
    

    But then you overwrite that variable by listing the contents of dir2:

    list = getFileList(dir2);
    

    You probably want to maintain two separate file lists:

    list2 = getFileList(dir2);
    

    and then loop over list2 independently. Unless the file names of images in dir and dir2 are related to one another somehow?

  • Relatedly: while looping over each ROI in the for (i=0; i<n; i++) loop, you write:

    path= dir2+list[f];
    

    But then you never do anything with this variable. That statement does not “change directories” but merely creates a string with the dir2 directory prefix concatenated with the current list[f] filename, then assigns the result to the path variable. You still need to do something with that variable (e.g., open that image?). Do the images in dir2 have exactly the same names as those in dir? Or are they different? If they are the same, then your code may be close to working. But if they are a separate collection of images with different names, you will need to list the files in dir2 separately, as described above, and work with the filenames from list2 somehow.

Thanks, This is helping me a lot, I’ve made some Huge progress since yesterday. I’ve cleaned up the code a lot and learned “A LOT” about coding. I mostly have the my macro working as wanted now, but I still have a problem with the Rois.

Is there an easy way to close rois related to one Image?

I have files that are correlated, In directory 1, I open my Images process them and then get an Roi (Or sometimes multiple) then I open files in Directory2 which have a the same base string name as the files in directory 1 process them and then I want a measurement from the rois form directory 1 related to my Image as the ouput. As I run my macro right now as It process down the directory it never clears out roi’s from the Image before it, so for instance if there is one ROi per base image by the time I’m at the 3rd Image I am getting 3 measurements… clearly with sometimes multiple rois per Image and lots of Images in a folder this is an unwanted amount of extraneous data…

Since I’ve worked on my code a lot since I last posted its currently looks like this:

dir = getDirectory("Choose input segment Directory ");    
list = getFileList(dir);                                         
print("number of files in dir1",list.length);                   
dir2 = getDirectory("Choose input Image Directory "); 
list2 = getFileList(dir2);               
extension2 = ".tif";   
print("number of files in dir2",list2.length);                  
dir3= getDirectory("Choose output Directory"); 

setBatchMode(true);        
for (f=0; f<list.length; f++) {  path = dir+list[f];                 
print("Name ofpath reading files fromfor dir1",path);                   
showProgress(f, list.length);     
if (!endsWith(path,"/")) open(path);  
if (nImages>=1) {                                 
t=getTitle();
\\ Several lines of code specifc to my Image procesing
run("Analyze Particles...", "size=4000-Infinity circularity=0.00-1.00 show=Outlines display include summarize add");
n=roiManager("count");
print("ROI_number=" + n); 
for (i=0; i<n; i++) {
    roiManager("Select", i);
roiManager("Save", dir3 + t + i +".zip")

path2=dir2+list2[f]; 
print("Name ofpath reading files from dir2",path2);   
if (!endsWith(path2,"/")) open(path2); 

\\several lines of code specific to my Image processing 
roiManager("Select",i );
run("Measure");
                  
     }                             
    }
    }

selectWindow("Results");
saveAs(dir3+"GlomareaandMME.txt");

Is there a way to get the count of roi associated with one Image or someone define the index other than to run though the list especially when the Number of Rois per Image changes? my final data set will have anywhere from no ROis in an Image to prob. ~50 on the high end.

Nope, the ROI Manager is global to all images. If you write a script in a language besides the ImageJ macro language, then there are ways to juggle multiple ROI managers at the same time, but the learning curve is steeper. It would be simpler to call:

roiManager("Deselect");
roiManager("Delete");

to delete all the ROIs in between the processing of each file. Or use the “Clear results” option of the Analyze Particles command to do so each time.

Another comment I forgot to mention last time: your if (nImages>=1) { does not do much, because you aren’t closing all the images beforehand, nor do you close the image after saving it. So as soon as one image is open, nImages will always be >= 1. The usual way of testing whether the file you want to open is an image is simply to check the extension, like so.

Lastly, comments start with //, not \\. If you use \\ then ImageJ will give an error when trying to run that line of code.

Thanks and YIKES, this already feels like it has a steep learning curve!

1 Like