ImageJ

From NoskeWiki
Jump to navigation Jump to search

About

ImageJ is an open source java-based image processing program designed for analysis of various microscope data. ImageJ is powerful in that it allows you to write your own simple plugins as .java files - many plugins have been written (see list) - most of these .jar files you can simply drag into the "plugins" directory. Due to its open source nature, many people have also "built" or taken from ImageJ, including the program "CellProfiler" (Carpenter et al 2006 [1]) and others listed here.


Pros:

  • Free and popular among light microscope users and already installed on many computers.
  • Appears to be powerful; has quite a few filters image processing algorithms and filters
  • Can record macros and write plugins
  • Can read and write all popular image formats: .tif, .jpg, .bmp etc.
  • Can make multiple selections using [t] and save selection as .roi files.
  • Can perform many type of analysis on selections

Cons:

  • Not a particularly nice or intuitive interface
  • Drawing tools quite crude - and selection based only - although can at least move selections
  • Does not open .mrc format (not without TomoJ plugin), although does open stacks of tif
  • Support isn't very well organized
  • Had trouble compiling plugins
  • Surprisingly buggy


Installation

ImageJ

You can download the latest stable version of ImageJ here and installation is as simple as running the .exe (on Windows) or copying the ImageJ folder into the Applications directory (on Mac).

Fiji..... (same thing, but with more plugins pre-installed)

Fiji is basically ImageJ with a large number of plugins and segmentation tools already built in. You can download the latest version of Fiji from here. If you intend to do lots of image segmentation, I recommend you install "Figi" instead of ImageJ - it behaves exactly the same as ImageJ, but can save you the effort of needing to install these extra plugins yourself.


Tricks and Examples

In this section I list out a few little tricks and example application of ImageJ/Fiji.


Creating a Macro to Batch Process a Directory

One of ImageJ's most useful features is the ability to record, write and run Macros. Macros are helpful whenever you find yourself applying the same actions over and over again. What can be especially useful is to record a macro and then set it up in such a way that you can batch process a bunch of images in one directory, and output with the same filenames to a different directory. There are instructions on how to record and apply instructions are here: How to apply a common operation to a complete directory. The basic steps are:

  1. Click Plugin > Macro > Record.
  2. Perform all your desired actions (in this case lets say we just want to run "Enhance Contrast").
  3. Save the file as "output.tif" in desired directory.
  4. In the Macro Recorder window change the name to "My_First_Macro.ijm", click "Create".
  5. Save "MyFirstMacro.ijm" by going to the "MyFirstMacro.ijm" window then File > Save.
  6. Close the "Recorder", open a new image and click "Run" in the "My_First_Macro.ijm" window to test it works.

At this stage your Macro should look like this:

run("Enhance Contrast", "saturated=0.4");                   // The important lines will be at the top.
saveAs("Tiff", "/Users/yourusername/Desktop/output.tif");   // And then you want to save the file.

At this stage you'll notice that running the Macro on any image overwrites exactly the same file ("output.tif"). What you need to do next is adapt your ".ijm" macro file to automatically process a whole directory of files and save each to a different file name. To do this modify your code so it looks like this:

input = "/Users/yourusername/Desktop/images/in/";         // |- Be sure to change these two paths to
output = "/Users/yourusername/Desktop/images/out/";       // |  to match your own directory names.

setBatchMode(true);
list = getFileList(input);
for (i = 0; i < list.length; i++)
    processFile(input, output, list[i]);
setBatchMode(false);

function processFile(input, output, filename)
{
    open (input + filename);                     // Opens our file in the "in" folder
    
    //----------- Put the main actions you recorded here: -----------
    run("Enhance Contrast", "saturated=2");
    //---------------------------------------------------------------
    
    saveAs("Tiff", output + filename);         // Saves the modified file into the "out" folder
    close();
}

Running this code should process all files in your "in" directory into the "out" directory you specified (with a matching file name). To run this Macro at a later time open Fiji then select Plugins > Marcos > Run.. then select your .ijm file.... or alternatively you can execute a Macro from the command line. On Mac OSX the command will look like this:

/Applications/Fiji.app/Contents/MacOS/fiji-macosx /Users/anoske/Desktop/images/My_First_Macro.ijm


Nucleus Separation Example

In light microscopy, biologists often stain the DNA in the cell nuclei with DAPI to help see the Nucleus. On the Fiji website there is a very nice article on how to count and isolate these nucleus. The full article is here: Nuclei Watershed Separation, and below are the key points from this article with a few optional steps added courtesy of Alex Perez:

  1. Install Fiji and open your DAPI stained image:
  2. optional - if your image looks washed out (i.e. it has low contrast): select (menubar) > Process > Enhance Contrast, then whatever value gives good contrast (try 2%).
  3. optional - if your image looks highly speckled: select Noise > Despeckle, and maybe even run a second time or consider binning by 2 (Image > Scale then halve the image size).
  4. Gaussian blur - select Process > Image > Gaussian Blur with sigma 2-3. TIP: The median filter is another good one to try
  5. Threshold - select Image > Adjust > Threshold, turn the checkbox for "dark background" on, adjusting the levels to select the boundaries as close as possible (try ~100 to 255) then click Apply which should give you white Nuclei and a black background.
  6. 8-bit - depending on your image it may need to be converted to 3-bit by going: Image > Type > 8-bit
  7. optional - if you find your Nuclei are a bit large you can erode them by going: Process > Binary > Erode or chose Dilate instead to make bigger.
  8. Invert - select Edit > Invert. NOTE: In their instructions they want you to leave the Nuclei black, but in *most* cases Watershed wants white object hence we need to invert.
  9. optional - if you notice some holes in your nucleus run: Process > Binary > Fill Holes. NOTE: Careful with this one as it might fill larger areas than you intend.
  10. Watershed - select Process > Binary > Watershed. This process should identify roughly round objects and split apart the touching nuclei. NOTE: If you find lines are drawn across your background hit undo (Edit > Undo), invert the image and retry.
  11. Analyze - select Analyze > Analyze Particles. Tick all of the checkboxes except "include holes" and "in situ Show" and set show to "Outline". Where it says size you should enter "20-Infinity" to ensure that tiny regions (less than 20 pixels) are not included. Click okay and in the ROI manager it will allow you to delete certain regions of interest. When you close the "Results" panel it will prompt you to save the results of sizes to a xls file.

Once you've done this a few times and are happy with all your parameters and results you can then create a Macro to apply these steps automatically to a series of files. Following the instructions in the section above "Creating a Macro to Batch Process a Directory", you can record a macro, then you'll want to save the macro as "Macro_DAPI_Watershed.ijm" and modify the code to look like this:

input = "/Users/yourusername/Desktop/images/in/";         // |- Be sure to change these two paths to
output = "/Users/yourusername/Desktop/images/out/";       // |  to match your own directory names.

setBatchMode(true);
list = getFileList(input);
for (i = 0; i < list.length; i++)
  DAPI_nuclei_threshold(input, output, list[i]);
setBatchMode(false);

function DAPI_nuclei_threshold(input, output, filename)
{
  open (input + filename);   // To open our file.
   
  //----------- Here are the lines we recorded:
  run("Enhance Contrast", "saturated=2");
  run("Gaussian Blur...", "sigma=3");
  setAutoThreshold("Default dark");
  //run("Threshold...");
  setThreshold(100, 255);
  run("Convert to Mask");
  run("Erode");
  run("Fill Holes");
  run("8-bit");
  //run("Invert");
  run("Watershed");
  
  //-- Uncomment these next few lines to save xls files too:
  //run("Analyze Particles...", "size=20-Infinity circularity=0.00-1.00 show=Nothing exclude clear record");
  //saveAs("Results", output + filename + ".xls");
   
  saveAs("Tiff", output + filename);
  close();
}

Running this code should process all files in your "in" directory into the "out" directory you specified. To run this Macro open Fiji then select Plugins > Marcos > Run.. then select your .ijm file.... or alternatively you can execute a Macro from the command line. On Mac OSX the command will look like this:

/Applications/Fiji.app/Contents/MacOS/fiji-macosx /Users/anoske/Desktop/images/Macro_DAPI_Watershed.ijm

In Alex's project this came in useful because he wanted to convert a 3D dataset from IMOD in MRC file format. While Fiji can open MRC files, not all its functions apply over 3D and it can't save MRC, so instead Alex used scripts to save the MRC to tifs, run the Image J macro, then joined all these new tifs back into a new MRC. In the final steps he then generate IMOD contours and surface meshes over the various boundaries. The unix commands for this were:

cd /Users/yourusername/Desktop/images/in/   # Goes to your "in" directory.
imod2tif vol.mrc vol                        # Converts MRC to a series of tifs called "vol.000.tif, vol.001.tif" etc.

###... RUN MACRO HERE (macro will take the images in the "in" folder and save them to the "out" folder)

cd ../out/                                  # Changes directory to your "out" folder
tif2mrc *tif vol_new.mrc                    # Inputs all the processed tif in the "out" folder and turns them into one MRC.
imodauto -f 1 vol_new.mrc vol.mod           # Will trace contours around all the black regions and save this to an new IMOD model file "vol.mod".
imodmesh -p 10 vol.mod vol.mod              # All contours which overlap by over 90% get meshed into the same surface.
imodsortsurf -s vol.mod vol_split.mod       # Will sort contours and split all surfaces into different objects with different colors.
imodmesh -p 10 vol_split.mod vol_split.mod  # Re-meshes the "split object" version of our .mod file.
3dmod ../in/vol.mrc vol_split.mod           # Opens this .mod file over the MRC file in 3dmod so we can see how well contours fit over original data.
3dmod ../in/vol.mrc vol_new.mrc vol.mod     # (Optional) use this line to flip between the original and processed MRC files.


Particle Analysis Example

An old colleague from Australia had an interesting problem where he wanted to mark up alveoli inside the lungs of a developing mouse embryo imaged with a light microscope. Apparently there are tens of these things, and many on top of each other; therefore making it difficult for automatic segmentation.

Instead I suggested marking them up manually by drawing circles, and using the following steps:

  • Open the image file. (eg: File >> Open Samples >> Embryos)
    • NOTE: Use [+] and [-] to zoom in and out.
  • Click: Analyze >> Set Scale and set the number of pixels / um (tick global).
  • (Optional) Add a scale bar by going: Analyze >> Tools >> Scale Bar (but be careful not to obscure image).
  • Hit save - for .tif files at least it appears to save the scale.
  • Select the "ellipse tool" (second from left) and draw the first circle.
  • Click: Edit >> Selection >> Add to Manager) and the "ROI manager" will open.
  • Toggle the "Show All" button on the ROI manager.
  • Continue to draw all circles and add with [t] one at a time.
    • NOTE: Holding shift you can make perfect circle, but be careful it also can make multiple circles in the same selection.
  • Click: Analyze >> Set Measurements and select desired properties (in this case only area is important).
  • Hold shift and select all the circles in the ROI manager and click "Measure"
  • Save this out output [ctrl+s] as an .xls file.
    • Within Excel you can determine the radius using the formula =SQRT(B2/PI()) and estimate the volume as =4/3*PI()*POWER(C3,3) .
  • With ALL the circles still selected click "Save" in the ROI manager (so you can come back to it later) to save the "RoiSet" as a .zip file.
    • NOTE: By default it will only try to save the current selection (shown in yellow) as a .roi file.

To reopen this you simple start ImageJ, then open the image file, then open the "RoiSet" .zip file. It also looks like you might also be able to batch process a number of these using: Plugins >> Analyze >> Batch Measure, but I haven't figured this out yet.


Turn an Image Sequence into an AVI Movie

Although ImageJ reads and writes many image formats, it only writes out one type of movie format - and that is AVI. Often AVI is all you'll want though (especially if you want a PowerPoint movie) and the instructions are as follows:

  1. Copy all the images/frames you want in a single directory with nothing else, and make sure they are in alphabetical order. For example: "frame000.jpg", "frame001.jpg", etc.
  2. Open ImageJ.
  3. Click File > Import > Image Sequence, navigate to the desired directory and click Select. There are some nice options here for scaling etc.
  4. Click File > Save As > AVI..., select your frames per second (25 is good if you have many frames) and save you AVI.

There are no options for AVI quality, but this is still very effective. See here for other methods to convert an image sequence to a movie.


Links


Acknowledgements: Alex Perez from NCMIR for finding and testing the Nucleus separation instructions