ImageJ batch processing: saving results of each image separately in the csv format - imagej

I have around 30 images and use ImageJ macros to analyse the particles (area, circularity, etc.) in the batch. From the macros script that I'm using, I'm not able to save the results separately, I mean one results.csv file per image.
Script:
fileName = getTitle();
run("Set Scale...", "distance=231 known=200 unit=um");
//setTool("rectangle");
run("Select All");
makeRectangle(0, 0, 2560, 1856);
run("Crop");
run("8-bit");
setAutoThreshold("Default");
run("Threshold...");
setThreshold(0, 116);
setOption("BlackBackground", false);
run("Convert to Mask");
//run("Close");
run("Analyze Particles...", "size=80-Infinity display exclude summarize add");
selectWindow("Results"); //activate results table
saveAs("Results", "C:/folder/Results.csv");

In the final line, your script will save a file called Results.csv and then overwrite it when you save the next image. So you need to construct a unique path for the Results for each image.
fileName = getTitle();
run("Set Scale...", "distance=231 known=200 unit=um");
//setTool("rectangle");
run("Select All");
makeRectangle(0, 0, 2560, 1856);
run("Crop");
run("8-bit");
setAutoThreshold("Default");
run("Threshold...");
setThreshold(0, 116);
setOption("BlackBackground", false);
run("Convert to Mask");
//run("Close");
run("Analyze Particles...", "size=80-Infinity display exclude summarize add");
selectWindow("Results"); //activate results table
// construct unique path here using fileName
path = "C:/folder/" + fileName + ".csv";
saveAs("Results", path);

Related

ImageJ macro has loop error during ROI analysis

I am trying to analyze confocal microscopy image for cFos analysis.
From maxstacked image, I took ROI of DAPI and enlarged the ROI to detect the degree of expression of transgene marker.
So I can find whether expression of transgene Piezo1 is related to increase of cFof level.
Here's the problem, when I took ROI twice by processing DAPI image differently worked well, but this has a consideration that the sequence of both ROI groups might be not same.
So I tried to enlarge the ROI from DAPI image, but then I am having trouble in loop analysis.
The macro runs for ever, but seems like to be saving same file names again and again, even with skipping some of the files in array.
Thank you for reading.
//The one is in trouble
dir1 = getDirectory("Choose Source Directory ");
dir2 = getDirectory("Choose Destination Directory ");
list = getFileList(dir1);
Array.sort(list);
run("Clear Results");
setBatchMode(true);
for (i=0; i<list.length; i++) {
if (endsWith(list[i],"tif")) {
showProgress(i+1, list.length);
open(dir1+list[i]);
title = getTitle();
saveFilename = replace(list[i], "_Maxstacked.tif","");
selectWindow(title);
run("Duplicate...", "title=DAPI duplicate channels=4");;
selectWindow("DAPI");
run("Subtract Background...", "rolling=80");
run("Gaussian Blur...", "sigma=1");
run("8-bit");
run("Auto Threshold", "method=Li white");
run("Convert to Mask");
run("Minimum...", "radius=8");
run("Maximum...", "radius=9");
run("Watershed");
run("Analyze Particles...", "size=20-1000 display exclude clear include overlay add");
roiN = roiManager("count");
if (roiN > 0) {
roiManager("Save", dir2+saveFilename+"_DAPI+_RoiSet.zip");
for(i=0; i<roiN; i++) {
roiManager("Select", i);
run("Enlarge...", "enlarge=2.7");
roiManager("Update");
}
roiManager("Save", dir2+saveFilename+"_DAPI+_for_Piezo1_RoiSet.zip");
roiManager("Delete");
roiManager("Delete");
}
close("*");
}
}
//The one worked
dir1 = getDirectory("Choose Source Directory ");
dir2 = getDirectory("Choose Destination Directory ");
list = getFileList(dir1);
Array.sort(list);
run("Clear Results");
setBatchMode(true);
for (i=0; i<list.length; i++) {
if (endsWith(list[i],"tif")) {
showProgress(i+1, list.length);
open(dir1+list[i]);
title = getTitle();
saveFilename = replace(list[i], "_Maxstacked.tif","");
selectWindow(title);
run("Duplicate...", "title=DAPI duplicate channels=4");
selectWindow(title);
run("Duplicate...", "title=DAPI_for_Piezo1 duplicate channels=4");
selectWindow("DAPI");
run("Subtract Background...", "rolling=80");
run("Gaussian Blur...", "sigma=1");
run("8-bit");
run("Auto Threshold", "method=Li white");
run("Convert to Mask");
run("Minimum...", "radius=8");
run("Maximum...", "radius=9");
run("Watershed");
run("Analyze Particles...", "size=20-1000 display exclude clear include overlay add");
roiN = roiManager("count");
if (roiN > 0) {
roiManager("Save", dir2+saveFilename+"_DAPI+_RoiSet.zip");
roiManager("Delete");
}
selectWindow("DAPI");
run("Subtract Background...", "rolling=80");
run("Gaussian Blur...", "sigma=1");
run("8-bit");
run("Auto Threshold", "method=Li white");
run("Convert to Mask");
run("Minimum...", "radius=8");
run("Maximum...", "radius=16");
run("Watershed");
run("Analyze Particles...", "size=20-1000 display exclude clear include overlay add");
roiN = roiManager("count");
if (roiN > 0) {
roiManager("Save", dir2+saveFilename+"_DAPI+_for_Piezo1_RoiSet.zip");
roiManager("Delete");
}
close("*");
}
}
I think you created an endless loop, because you use i both times. So in the second for loop the i is set back to 0. Just try changing it in the second one (you can choose whatever letter or word).
...
for(n=0; n<roiN; n++) {
roiManager("Select", n);
run("Enlarge...", "enlarge=2.7");
roiManager("Update");
}
...

ImageJ: Export list of histogram for multiple Images

after hours of trying and searching related topics, I don't get further. I am trying to create a small ImageJ script that splits channels of a picture, saves on .tif version with enhanced contrast (this part works) AND creates a histogram and saves it values as .csv (this part does not work, it doesn't save anything).
I have no idea why it doesn't work so here is my whole code.
input = getDirectory("Input directory");
output = getDirectory("Output directory");
Dialog.create("File type");
Dialog.addString("File suffix: ", ".tif", 5);
Dialog.show();
suffix = Dialog.getString();
processFolder(input);
function processFolder(input) {
list = getFileList(input);
for (i = 0; i < list.length; i++) {
if(File.isDirectory(list[i]))
processFolder("" + input + list[i]);
if(endsWith(list[i], suffix))
processFile(input, output, list[i]);
}
}
function processFile(input, output, filename) {
print("Processing: " + input + filename);
open(input + filename);
run("Split Channels");
selectWindow(filename+" (blue)");
close();
selectWindow(filename+" (green)");
close();
selectWindow(filename+" (red)");
run("Histogram");
getHistogram(values, counts, 256);
saveAs("Results", output + "Histogram of " + filename + ".csv");
close();
saveAs("TIFF", output+ "processed_" + filename);
selectWindow("processed_" + filename);
close();
}
I appreciate every input. Cheers!
not sure you can save it as a csv file using the IJ macro language. However here is some code to do the same thing but save it as a txt file (this example only takes the value from 255)
getStatistics(mean, min, max, std, histogram);
white=histogram[255];
// list2 is the list of images in a for loop - adds image name to results
print(white,",", list2[j]+" smi31");
selectWindow("Log");
saveAs("txt", file1+"Result");
Hope this is helpful :-)

Java ImageIO Read and Write compressed Tiff files with CIE lab colorspace

I actually try to read and write compressed tif-files with CIE Lab colorspace.
Unfortunally if I try to just read and after this write the tif back to the HDD the color is different from the soure tif.
Is the ImageIO lib able to read and write compressed tif files with CIE lab color space?
If it is possible I fear that something is wrong with the code. In the singleTiffs list are at least one tiff-ImageInputStream which is created in this way:
ImageIO.createImageInputStream(testTiff)
Would be great if someone could help me. Thanks a lot!
// Get iterator for input images
Iterator<ImageInputStream> iterator = singleTiffs.iterator();
// Get tif writer and set output to file
Iterator writers = ImageIO.getImageWritersByFormatName("tiff");
ImageWriter writer = (ImageWriter) writers.next();
ImageOutputStream ios = ImageIO.createImageOutputStream(newMultiPageTIFF);
writer.setOutput(ios);
// Write each image out to the new file
boolean firstImage = true;
while(iterator.hasNext())
{
ImageInputStream iis = iterator.next();
// Get a reader for the stream
Iterator readers = ImageIO.getImageReaders(iis);
ImageReader reader = (ImageReader) readers.next();
reader.setInput(iis);
// Read the stream metadata
// IIOMetadata streamMetadata = reader.getStreamMetadata();
// Read the image metadata - we are assuming there is only one image
// in the tiff
IIOMetadata imageMetadata = reader.getImageMetadata(0);
// Set up the writeParam
TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_COPY_FROM_METADATA);
BufferedImage bi = reader.read(0, null);
IIOImage image = new IIOImage(bi, null, imageMetadata);
if(firstImage == false)
writer.writeInsert(-1, image, tiffWriteParam);
else
{
writer.write(null, image, tiffWriteParam);
firstImage = false;
}
// Done writing all images for this image
reader.dispose();
}
// End writing of all files
writer.dispose();

Imagej macro to save data generated by results and log pages into the same end excel file

I have created a macro that generates results both in the log and results pages. I need a macro that saves both the results and log files into one big excel file and is organized by image name.
input=getDirectory("Choose Source Directory ");
list = getFileList(input);
for (i = 0; i < list.length; i++)
rootangle(input, list[i]);
function angle (input,filename){
open (input + filename);
setTool("angle");
for (i = 0; i < 5; i++){
waitForUser("Select Angle Points");
run("Set Measurements...", " display redirect=None decimal=3");
//run("Measure");
}
setTool("multipoint");
waitForUser("Count");
run("Set Measurements...", " display redirect=None decimal=3");
run("Measure");
}
setTool("line");
waitForUser("Measure");
run("Set Measurements...", " display redirect=None decimal=3");
run("Measure");
}
setTool("freehand");
waitForUser("Distance");
run("Set Measurements...", " display redirect=None decimal=3");
run("Measure");
}
setTool("polyline");
waitForUser("Draw");
run("Fit Spline", "straighten");
getSelectionCoordinates(x, y);
for (i=0; i<x.length; i++)
print(i+" "+x[i]+" "+y[i]);
}
dir=getDirectory("image");
name = "Results";
index = lastIndexOf(name, "\\");
if (index!=-1) name = substring(name, 0, index);
name = name + ".xls"; ///can change xls to csv, txt, etc.
saveAs("Measurements", dir+name);
close();
}
run("Clear Results");
In this macro the polyline generates many many x,y coordinates for each image that may be bulky for the excel file. These coordinates can be listed on one line in the results excel file.
Is there a way you can add manual annotation to the label in the results page?
Also, is there a way you can add pose measurement functions? Like divide the numbers by 2, etc before creating the excel file?
I wrote a macro which saves results of ROI multimeasures to the log window. Since I only wanted specific results (the highest three Raw Integrated Densities), I had my code use getResult("Column Label", row) to get the results out, manipulate them, and then print to the log using print("stuff to print"). At the end, I saved the log as a csv, which one can open in excel. Just use commas to separate

How to get threshold value used by auto threshold Plugin

I have the following code, where I read images from directory and use ImageJ Auto Threshold plugin to segment my images.
dir = getDirectory("path");
list = getFileList(dir);
for (i=0; i<list.length; i++)
{
if (endsWith(list[i], ".tif"))
{
open(dir + list[i]);
run("8-bit");
run("Gaussian Blur...", "sigma=2");
setAutoThreshold("Otsu dark");
run("Convert to Mask");
saveAs("TIFF", dir+list[i]);
close();
}
}
I would like to get the threshold value using "Otsu dark" method, and modify that value (e.g. scale it by a factor) and apply it to my images for segmentation.
In an ImageJ macro, use the getThreshold(lower,upper) and setThreshold(lower,upper) methods (here's the documentation).
Your code would look like this then:
dir = getDirectory("path");
list = getFileList(dir);
factor = 1.5;
for (i=0; i<list.length; i++)
{
if (endsWith(list[i], ".tif"))
{
open(dir + list[i]);
run("8-bit");
run("Gaussian Blur...", "sigma=2");
setAutoThreshold("Otsu dark");
getThreshold(lower,upper);
setThreshold(lower,upper*factor);
run("Convert to Mask");
saveAs("TIFF", dir+list[i]);
close();
}
}
If you plan to do more complicated things, consider using another scripting language like the ones provided by Fiji.

Resources