ImageJ API:从图像获取RGB值
问题描述:
我试图从ImagePlus
对象获取RGB值。我得到一个异常错误,当我试图做到这一点:ImageJ API:从图像获取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
...任何想法?^_^
答
由于ip.getColorModel()不返回IndexColorModel对象,而是ColorModel对象,因此会出现此错误。
为了得到IndexColorModel的对象,你应该使用下面的代码:
IndexColorModel icm = ip.getDefaultColorModel();
这应该给你一个IndexColorModel的,根据ImageJ API。
答
ColorProcessor包含的方法
getChannel()
得到红色,绿色或蓝色通道。
要获得ColorProcessor,您可以将您的处理器投射到ColorProcessor。
ColorProcessor cp = (ColorProcessor) ip;
它会抛出一个错误,如果图像是一个灰度虽然。