How to only select a window if that window exists, and otherwise skip it?

I am trying to write a script that will batch process a lot of TIFF images (split the color channels, measure the densitometry of each channel, save the measures). Some of my images have two color channels and some have three, and I can’t figure out how to get the script to process the third window (if it exists), and skip on to finish the processing if there is no third window. Here is the code I have so far:

// Select the folder containing your images
dir1 = getDirectory("Choose Source Directory ");
list = getFileList(dir1);
// Select or create output folder
Output = getDirectory("Choose the output folder ");
//delineate batch processing
for (k = 0; k<list.length; k++) { //list length is as many images as there are in the folder
showProgress(k+1, list.length);
open(dir1+list[k]); //open the first image (and then the next etc, after running)
imageName = getTitle(); //set “imageName” as the original name of each image

run("Split Channels");
selectWindow("C1-"+ imageName); //Select red (or Far Red) window
run("Measure"); // run "Measure" on red (or Far Red) window
selectWindow("C2-"+ imageName); //Select green (or blue) window
run("Measure"); // run "Measure" on green (or blue) window
if (File.exists("C3-"+ imageName)){ //If it exists, select blue window
(selectWindow("C3-"+ imageName))
run("Measure"); // if it exists, run "measure" on blue window
outName = imageName + "dens"; //still appends "dens" to ".tif" instead of file name before ".tif"
saveAs("Results", Output + outName); //Save each measure into Output folder separately for each image
close("Results"); // close Measure window
while(nImages>0)close(); // close all open images 

} // still stops after CIE? --> doesn’t do all images in the folder, only 1/3

Error 1: When I unnest the “if” statement, instead of running “Measure” on C3 window, it runs it twice on C2 window. It used to not run a third measure at all – it just ignored the “if” statement
about C3 when I had the “if” commands nested. Now it runs the third measure,
but on C2 instead of C3.

Error2: Stops 1/3 of the way through the files in the folder, says it can’t find
the file or the file is not compatible. File name is “‘Folder I’m working in’/deskstop.ini”

Error3: Adds “dens” to the end of the file name after “.tif” instead of before “.tif”

Have a look at the following functions:

Returns *true* if the image with the specified ID is open.

Returns *true* if the window with the specified title is open.

from the ImageJ API:


@Bio7 Thank you, that worked!

I looked high and low for a function like that. I don’t know how I missed it. That change seemed to fix the issue of the program stopping a third of the way through my files, too, for some reason.