在java中将RGB图像转换为gray_scale HSV

时间:2014-03-28 15:32:23

标签: java image hsv

我想将RGB图像转换为HSV并最终返回gray_scale图像。我有以下代码来阅读和转换我的图像:

    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图像需要做什么?以上是正确的方法吗?

1 个答案:

答案 0 :(得分:1)

使用JavaCV [java的OpenCV包装]

非常容易
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;

公共课GrayScale {

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();

}

}