Randomized ROI Macro Specifications

Hey there,

I have been playing around with a macro that places randomized ROIs of known size onto an image. However, I would like to optimize the final product in two ways and I’m wondering if anyone can tell me how I might be able to fix it. I would like to make the lines of the boxes thinner and remove the numbers from inside (place them elsewhere or remove entirely). Any help is appreciated, thank you!

Here is an example image:

And the macro:

run("Select None");     

  saveSettings(); 
  original=getTitle(); 
  setForegroundColor(255,0,0); 

  width = getWidth()-525.788;   // width of the randomly placed ROI 
  height = getHeight()-525.788; // height of the randomly placed ROI 
  RoisN =6; // number of ROIs 
  trials=100 ; //maximum trials to avoid infinite loop 

  i=0; 
  j=0; 

  xa=newArray(RoisN); 
  ya=newArray(RoisN); 

  run("Duplicate...", "title=Reference"); 




  selectWindow("Reference"); 
  run("8-bit"); //makes it greyscale 
  run("RGB Color"); //RGB to display colours 
  run("Restore Selection"); 
  run("Make Inverse"); 
  run("Fill"); 
  run("Select None"); 
  



   while (i<RoisN && j<trials){ 
        w = 525.788; 
        h = 525.788; 
        x = random()*width; 
        y = random()*height; 
        j++; 
        //Check for pixels with value (255,0,0): 
        flag= -1; 
        makeRectangle(x, y, w, h); 
        //Scanning the rectangle perimeter should be faster than scanning the whole box. 
        //This is slower, as checks all the points in the box: 
        for (xs=x;xs<x+w;xs++){ 
            for (ys=y;ys<y+h;ys++){ 
                if (getPixel(xs,ys)==-65536) // pixel is (255,0,0) 
                    flag=0; 
            } 
        } 
        if (flag==-1){ 
            xa[i]=x; 
            ya[i]=y; 
            run("Fill"); 
            i++; 
        } 
   } 
      

  close(); 
  selectWindow(original); 
  setForegroundColor(255,255,0); 
  for (j=0;j<i;j++){ 
    makeRectangle(xa[j], ya[j], w, h); 
      run("Measure"); 
      run("Label"); 
  } 
 restoreSettings();       
 run("Select None"); 
 run("Jpeg...", "save"); 
 run("Close");

Hi @A_Hopf,

I may answer half of your question: For removing the numbers, you just need to remove the line
run("Label");

If you want to place the numbers somewhere else: there is an example macro online showing you how to change font sizes and writing texts…
https://imagej.net/macros/TextDemo.txt

Is was linked from this website you may already know:
https://imagej.net/developer/macro/functions.html#setFont

Cheers,
Robert

2 Likes

Thank you very much @haesleinhuepf, that solved both of my issues!

1 Like