Need help with batch image calculations

Hi, I’m pretty new to ImageJ and I’m having some trouble with batch processing using the image calculator. I have a set of images that I want to subtract the background from. Both the original images and the binary versions of those images have the same name and are .tif files, but they are saved in separate folders. I’ve used the recorder to try to piece together a macro, but I haven’t been able to make them work. I have found a few different threads that discuss a similar topic, but since I’m very unfamiliar with creating macros, I’m having trouble tweaking them based on what my files are named, etc.

This is what I have so far (adapted from something I saw on Reddit), but I’m fairly certain there are a number of errors because of the changes that I made:

dir1 = “C:\/Users/kate/Desktop/ImageJTest/\”;
dir2 = “C:\/Users/kate/Desktop/ImageJTestBinary/\”;
dir3 = “C:\OutputFiles\”;
list = getFileList(dir1);

for(i=1;i<=list.length;i++){
file1name = “x.tif”;
file2name = “x.tif”;
open(dir1 + file1name);
open(dir2 + file2name);
imageCalculator(“Subtract create”, file1name, file2name);
saveAs(“TIF”,dir3+“image”+i+"_subtracted.tif");
run(“Close All”);

Thank you in advance for any help!

Hi
@keg018
1;To open images in a folder
Read this tread:

2; Test this and please report.

requires("1.52t")
setBackgroundColor(0,0,0);
setOption("BlackBackground",true);

dir1 = getDirectory("Select input Directory1");    
list1 = getFileList(dir1);                                        
print("number of files in dir1:",list1.length);
print("The name of the folder input1is:"+dir1);  
                
dir2 = getDirectory("Select input Directory2 ");
list2 = getFileList(dir2);              
print("number of files in dir2:",list2.length);  
print("The name of the folder input2 is:"+dir2);  
            
dir3= getDirectory("Select output Directory");
print("The name of the folder output is:"+dir3);  

setBatchMode(true);  

Counter=0;
for(i=0;i<list1.length;i++)

{
Counter++;
print("list1"+i+"="+ list1[i]);
    open( dir1 + list1[i] );
rename("1"+i);
j=i;
print("list2"+j+"="+ list2[j]);
    open( dir2 + list2[j] );
rename("2"+j);
imageCalculator("Add create","1"+i,"2"+j);
saveAs("Jpeg", dir3+"Result of 1"+j+".jpg");
}
print("Counter="+Counter);
setBatchMode(false);

// Close all open image
while(nImages>0){
selectImage(nImages);
close();
}
exit("It's Over");