Java RGB Color Convert To RGBtoHSV(float[] hsv, float[] rgb)

Here you can find the source of RGBtoHSV(float[] hsv, float[] rgb)

Description

Convert an RGB color to HSV representation.

License

BSD License

Declaration

public static void RGBtoHSV(float[] hsv, float[] rgb) 

Method Source Code

//package com.java2s;
//License from project: BSD License 

public class Main {
    private static int RED = 0;
    private static int GREEN = 1;
    private static int BLUE = 2;
    private static float EPSILON = 1.0e-6f;

    /** //from  w  w  w.ja va  2 s .c  om
     * Convert an RGB color to HSV representation. It is assumed that all RBG
     * and HSV values are in the range 0-1 (as opposed to the typical HSV ranges
     * of [0-360], [0-100], [0-100]).
     */
    public static void RGBtoHSV(float[] hsv, float[] rgb) {

        float r = rgb[0];
        float g = rgb[1];
        float b = rgb[2];

        float h, s, v, diff;

        int minIdx = 0;
        int maxIdx = 0;
        float maxCol = r;
        float minCol = r;
        if (g > maxCol) {
            maxCol = g;
            maxIdx = GREEN;
        }
        if (g < minCol) {
            minCol = g;
            minIdx = GREEN;
        }
        if (b > maxCol) {
            maxCol = b;
            maxIdx = BLUE;
        }
        if (b < minCol) {
            minCol = b;
            minIdx = BLUE;
        }

        diff = maxCol - minCol;
        /* H */
        h = 0.0f;
        if (diff >= EPSILON) {
            if (maxIdx == RED) {
                h = ((1.0f / 6.0f) * ((g - b) / diff)) + 1.0f;
                h = h - (int) h;
            } else if (maxIdx == GREEN) {
                h = ((1.0f / 6.0f) * ((b - r) / diff)) + (1.0f / 3.0f);
            } else if (maxIdx == BLUE) {
                h = ((1.0f / 6.0f) * ((r - g) / diff)) + (2.0f / 3.0f);
            }
        }
        /* S */
        if (maxCol < EPSILON)
            s = 0;
        else
            s = (maxCol - minCol) / maxCol;

        /* V */
        v = maxCol;

        hsv[0] = h;
        hsv[1] = s;
        hsv[2] = v;
    }
}

Related

  1. rgbToHsl(int red, int green, int blue)
  2. rgbToHsv(byte[] rgb, float[] hsv)
  3. RGBtoHSV(double r, double g, double b)
  4. RGBtoHSV(float r, float g, float b, float[] result)
  5. RGBToHSV(float... rgb)
  6. RGBtoHSV(int r, int g, int b, double hsv[])
  7. rgbToHsv(int red, int green, int blue)
  8. RGBtoHSV(int red, int green, int blue)
  9. RGBToHSV(int red, int green, int blue, float[] hsv)