简体   繁体   中英

How to open an image with ImageJ in java

I want to analyse images using the ImageJ framework in java. How can I open an image? I need to have an ImageProcessor object to be able to generate a histogram. Here is the code I have so far:

public void run(ImageProcessor ip) {
        int[] H = new int[256]; // histogram array
        int w = ip.getWidth();
        int h = ip.getHeight();

        for (int v = 0; v < h; v++) {
            for (int u = 0; u < w; u++) {
                int i = ip.getPixel(u, v);
                H[i] = H[i] + 1;
            }
        }

        // ... histogram H[] can now be used
    }

I work with medical grayscale images where a ColorProcesser is not appropriate. In that case I use

Opener opener = new Opener();  
String imageFilePath = "somePath";
ImagePlus imp = opener.openImage(imageFilePath);
ImageProcesser ip = imp.getProcessor(); // ImageProcessor from ImagePlus 

I didn't see anything specifying how you wanted to open the image but Iv'e added some code below that will open the folder opener window and you can navigate to a folder of images (I think its mainly used for image stacks but you could just make the stack size 1 and it should work to open a single image).

import ij.plugin.FolderOpener;

// Do this stuff in your run method
FolderOpener fo = new FolderOpener(); // create FolderOpener object
ImagePlus your_imgPlus; // create ImagePlus object
your_imgPlus = fo.open(null); // call FolderOpener.open()

The null argument in open() allows the folder selection window to open, you can also use a file path as an argument.

Create a java.awt.Image first and then use it to construct a ColorProcessor (subclass of ImageProcessor ) object.

Image myImage;
// instantiate myImage
ImageProcessor processor = new ColorProcessor(myImage);
 File inputFile = new File("someImage.png");
    Image someImage = null;
    try {
        someImage = ImageIO.read(inputFile);
    } catch (IOException e) {
        e.printStackTrace();
    }
    ImagePlus imagePlus = new ImagePlus();
    imagePlus.setImage(someImage);
    ColorProcessor processor = (ColorProcessor) imagePlus.getProcessor();

The answers are old so maybe there has been some changes, but I prefer using the static method IJ.openImage(java.lang.String path_to_file) http://rsb.info.nih.gov/ij/developer/api/ij/IJ.html . This method returns an ImagePlus object.

I use absolute file paths myself but I suspect relative ones should work fine too. If you want the ImageProcessor associated with the ImagePlus you call getProcessor().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM