2014-03-28 89 views
0

我想要將RGB圖像轉換爲HSV並最終返回gray_scale圖像。我已經得到了下面的代碼,以便讀取和轉換我的形象:在java中將RGB圖像轉換爲gray_scale HSV

BufferedImage lum = new BufferedImage(original.getWidth(), original.getHeight(), original.getType()); 

    for(int i=0; i<original.getWidth(); i++) { 
     for(int j=0; j<original.getHeight(); j++) { 

      // Get pixels by R, G, B 
      alpha = new Color(original.getRGB(i, j)).getAlpha(); 
      red = new Color(original.getRGB(i, j)).getRed(); 
      green = new Color(original.getRGB(i, j)).getGreen(); 
      blue = new Color(original.getRGB(i, j)).getBlue(); 

      float[] hsv = Color.RGBtoHSB(red, green, blue, null); 
      int hue = (int) Math.round(360 * hsv[0]); 

      red = (int) (0.21 * red + 0.71 * green + 0.07 * blue); 
      // Return back to original format 
      newPixel = colorToRGB(alpha, red, red, red); 

      // Write pixels into image 
      lum.setRGB(i, j, hue); 

     } 
    } 

    return lum; 

什麼都爲了返回HSV gray_scale形象呢?上述是否是正確的方式?

+0

如果你只是轉換成灰度圖,爲什麼還要用HSV? –

+0

我實際上對使用色調通道感興趣。 –

+0

是否可以從計算出的hsv頻道創建一個bufferedimage?轉換後的過程。 –

回答

1

這是很容易與JavaCV [OpenCV的包裝爲Java]

IplImage originalImage = cvLoadImage("path of input image", 1); 
IplImage grayImage = IplImage.create(originalImage.width(),originalImage.height(), IPL_DEPTH_8U, 1); 
cvCvtColor(originalImage, grayImage, CV_BGR2GRAY); 
cvSaveImage("path of output image", originalImage); 

,或者如果你想實現它在純java,使用下面的代碼

import com.sun.image.codec.jpeg.JPEGCodec; 
import com.sun.image.codec.jpeg.JPEGImageDecoder; 
import com.sun.image.codec.jpeg.JPEGImageEncoder; 
import java.awt.color.ColorSpace; 
import java.io.*; 
import java.awt.image.*; 
import javax.imageio.ImageIO; 

公共類灰度{

public static void convertToGrayscale() throws Exception { 

    JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(new FileInputStream(new  File("a.jpg"))); 
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(new FileOutputStream("b.jpg")); 
    BufferedImage sourceImg = decoder.decodeAsBufferedImage(); 
    BufferedImageOp op = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null); 
    BufferedImage destImg = op.filter(sourceImg, null); 
    encoder.encode(destImg); 
    decoder = null; 
    encoder = null; 

}

public static void main(String[] args) throws Exception { 

    GrayScale.convertToGrayscale(); 

} 

}

+0

基本上我想讀取我的bufferedImage並返回色調通道。 –