Why for loop in imagej macro language is not working one after the other?

fiji
imagej
macro

#1

I need the to open images in a folder and do some analyses and close and open the next image and so on. But what I found is that it opens all images simultaneously and do not close them. Any help to fix this issue is appreciated.
Here is my code:

 for (j=1;j<4; j=j+1){
path="C:/Users/"+j+".tif";
open(path);
imagename=""+j+".tif";
selectWindow(imagename);
close();
}

#2

Your problem could be here:

imagename=""+j+".tif";

Assuming you put the double quote as you were getting an error.
If you want file: 1.tiff,
As you cannot add a number and a string, you have to convert j or the number 1 to a string. Use d2s function in ImageJ to convert j to a string and then add it to “tif” to get your file name.

It should be
imagename=d2s(j,0)+".tif";
Try that and see if it fixes your problem.


#3

Tried it. Unfortunately did not solve the problem. I think both your and my definition of imagename is right and the problem is not the definition. I feel for loop is doing the process for all js simultaneouly. but I need to open my image do something close and then open another image and so on. But it does not do these steps one after the other.


#4

Actually, I was so focused on the string name,did you try
> close(imagename);

instead of

selectWindow(imagename);
close();

#5

That is very odd that it isn’t working for you. I just tried it copying verbatim what you posted (except for the file path) and had absolutely no issues. That being said, I am using Ubuntu, not Windows. One thing I would have though might make a difference is that your path is not in standard Windows syntax. It should be C:\Users\. Though, I would have thought the path would only impact opening; which is sounds like you have no problems with.

Regarding how you are concatenating your index into a filename, that should work. At least, it did in older versions of ImageJ. The issue is when you to number+string; string+number is fine as ImageJ (or Java) correctly assumes you want to cast the number to a string.


#6

I also can’t recreate this problem. I copied it verbatim including the file path on a Windows system (created 1.tif, 2.tif, 3.tif in my C:/Users folder) and it ran fine.


#7

Is this part of a larger macro? If so, please post the whole thing. Your issue might be a syntax error somewhere else in the macro.


#8

Yeah it is part of a larger macro. It is solved I had nan as some elements of array that’s why it did not work. Thank you all