未显示RGB到HSV值

时间:2017-02-27 03:52:02

标签: java image colors

我正在尝试转换图像的RGB值并获取它的HSV值。我试图在不使用Color.RGBtoHSB的情况下执行此操作,因为我不喜欢浮点值,我希望数字在0-255范围内。当我运行这个程序时,即使我要求它打印输出值,我的转换算法也没有打印出来。

public void splitChannels() {

    Mat firstImage = Imgcodecs.imread("darkGreen.jpg");
    Imgproc.cvtColor(firstImage, firstImage, Imgproc.COLOR_BGR2RGB);
    int width = 20;
    int height = 20;
    Rect roi = new Rect(100,100, width, height);
    Mat smallImg = new Mat(firstImage, roi);

   Imgproc.cvtColor(smallImg,smallImg,Imgproc.COLOR_BGR2RGB);
    // 3 channels in smallImg
    int channels = smallImg.channels();

    int totalBytes = (int)(smallImg.total() * smallImg.channels());

    byte buff[] = new byte[totalBytes];
    smallImg.get(0, 0, buff);

    for (int i=0; i< height; i++) {
        // stride is the number of bytes in a row of smallImg
        int stride = channels * width;
        for (int j=0; j<stride; j+=channels) {
            int r = buff[(i * stride) + j];
            int g = buff[(i * stride) + j + 1]; 
            int b = buff[(i * stride) + j + 2];

            RGBtoHSV(r, g, b);

        } 
    } 
}

private int[] RGBtoHSV(int r, int g, int b){
    int computedH = 0;
    int computedS = 0;
    int computedV = 0;
    int[] HSVarr = new int[3];


    HSVarr[0] = computedH;
    HSVarr[1] = computedS;
    HSVarr[2] = computedV;
    if(r< 0 || g< 0 || b< 0 || r> 255 || g>255 || b> 255){
        System.err.println("RGB values must be in range 0 to 255");
    }

    r=r/255; g=g/255; b=b/255;
    int minRGB = Math.min(r, Math.min(g, b));
    int maxRGB = Math.max(r, Math.min(g, b));

    // Black-gray-white
    if(minRGB==maxRGB){
        computedV = minRGB;
        return  HSVarr;
    }

    int d = (r==minRGB) ? g-b : ((b==minRGB) ? r-g : b-r);
    int h = (r==minRGB) ? 3 : ((b==minRGB) ? 1 : 5);
    computedH = 60*(h - d/(maxRGB - minRGB));
    computedS = (maxRGB = minRGB)/maxRGB;
    computedV = maxRGB;

    System.out.println("H: " + computedH + " V: "+ computedS +" S: " + computedV);
    return HSVarr;
}

1 个答案:

答案 0 :(得分:1)

  

我正在尝试转换图像的RGB值并获取它的HSV值。我试图在不使用Color.RGBtoHSB的情况下这样做,因为我不喜欢浮点值。

Color.RGBtoHSB(...)方法创建一个包装器方法,以将浮点值转换为适当的int值。

类似的东西:

import java.awt.*;

public class Main
{
    public static void main(String[] args) throws Exception
    {
        int[] hsb = RGBtoHSB(0, 0, 255);

        for (int value: hsb)
            System.out.println( value );
    }

    public static int[] RGBtoHSB(int red, int green, int blue)
    {
        float[] hsbFloat = Color.RGBtoHSB(red, green, blue, null);
        int[] hsbInt = new int[3];

        hsbInt[0] = Math.round( hsbFloat[0] * 360 );
        hsbInt[1] = Math.round( hsbFloat[1] * 100 );
        hsbInt[2] = Math.round( hsbFloat[2] * 100 );

        return hsbInt;
    }
}