【问题标题】:ImageJ API: Getting RGB values from imageImageJ API:从图像中获取 RGB 值
【发布时间】:2012-07-19 15:58:02
【问题描述】:

我正在尝试从ImagePlus 对象中获取 RGB 值。尝试执行此操作时出现异常错误:

import ij.IJ;
import ij.ImagePlus;
import ij.plugin.filter.PlugInFilter;
import ij.process.ColorProcessor;
import ij.process.ImageProcessor;
import java.awt.image.IndexColorModel;

public class ImageHelper implements PlugInFilter {

    public int setup(String arg, ImagePlus img) {
        return DOES_8G + NO_CHANGES;
    }

    public void run(ImageProcessor ip) {

        final int r = 0;
        final int g = 1;
        final int b = 2;

        int w = ip.getWidth();
        int h = ip.getHeight();

        ImagePlus ips = new ImagePlus("C:\\Lena.jpg");
        int width = ips.getWidth();
        int height = ips.getHeight();
        System.out.println("width of image: " + width + " pixels");
        System.out.println("height of image: " + height + " pixels");

        // retrieve the lookup tables (maps) for R,G,B
        IndexColorModel icm = (IndexColorModel) ip.getColorModel();

        int mapSize = icm.getMapSize();
        byte[] Rmap = new byte[mapSize];
        icm.getReds(Rmap);
        byte[] Gmap = new byte[mapSize];
        icm.getGreens(Gmap);
        byte[] Bmap = new byte[mapSize];
        icm.getBlues(Bmap);

        // create new 24-bit RGB image
        ColorProcessor cp = new ColorProcessor(w, h);
        int[] RGB = new int[3];
        for (int v = 0; v < h; v++) {
            for (int u = 0; u < w; u++) {
                int idx = ip.getPixel(u, v);
                RGB[r] = Rmap[idx];
                RGB[g] = Gmap[idx];
                RGB[b] = Bmap[idx];
                cp.putPixel(u, v, RGB);
            }
        }
        ImagePlus cwin = new ImagePlus("RGB Image", cp);
        cwin.show();
    }
}

异常来自这一行:

 IndexColorModel icm = (IndexColorModel) ip.getColorModel();

例外:

线程“主”java.lang.ClassCastException 中的异常: java.awt.image.DirectColorModel 无法转换为 java.awt.image.IndexColorModel

...有什么想法吗? ^_^

【问题讨论】:

    标签: java image-processing rgb imagej


    【解决方案1】:

    发生错误是因为 ip.getColorModel() 没有返回 IndexColorModel 对象,而是 ColorModel 对象。

    要获取 IndexColorModel 对象,您应该使用以下代码:

    IndexColorModel icm = ip.getDefaultColorModel();
    

    根据ImageJ API,这应该会给你一个 IndexColorModel。

    【讨论】:

      【解决方案2】:

      ColorProcessor 包含方法

      getChannel() 
      

      获取红色、绿色或蓝色通道。

      要获得 ColorProcessor,您可以将处理器转换为 ColorProcessor。

      ColorProcessor cp = (ColorProcessor) ip;
      

      如果图像是灰度图像,则会引发错误。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-19
        • 1970-01-01
        • 2013-07-10
        • 2016-02-15
        • 2014-11-29
        • 1970-01-01
        相关资源
        最近更新 更多