2012-07-15 278 views
0

我試圖從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

...任何想法?^_^

回答

1

由於ip.getColorModel()不返回IndexColorModel對象,而是ColorModel對象,因此會出現此錯誤。

爲了得到IndexColorModel的對象,你應該使用下面的代碼:

IndexColorModel icm = ip.getDefaultColorModel(); 

這應該給你一個IndexColorModel的,根據ImageJ API

0

ColorProcessor包含的方法

getChannel() 

得到紅色,綠色或藍色通道。

要獲得ColorProcessor,您可以將您的處理器投射到ColorProcessor。

ColorProcessor cp = (ColorProcessor) ip; 

它會拋出一個錯誤,如果圖像是一個灰度雖然。