Pages

July 16, 2013

RGB to HSV Color space conversion

Color space conversions is too complicated for me, so I made this useful function.
You need:
- http://objective-c-functions.blogspot.com/2013/06/helpful-color-struct-rgb-hsv.html
- http://objective-c-functions.blogspot.com/2013/07/max-value-in-array.html
- http://objective-c-functions.blogspot.com/2013/07/min-value-in-array.html


/** Convert from RGB to HSV.

 RGB range is [0;255] for all channels. HSV range is [0;360] for H and [0;100] for S and V.

 @param col RGB color to convert.
 @return Returns HSV color.
 @see rgbFromHsv:

 */
+ (COLOR_HSV)hsvFromRgb:(COLOR_RGB)col {

    COLOR_HSV ret;

    CGFloat min, max, delta;

    NSNumber *r = [NSNumber numberWithFloat:col.r];
    NSNumber *g = [NSNumber numberWithFloat:col.g];
    NSNumber *b = [NSNumber numberWithFloat:col.b];

    min = [LMFunctions minValueInArray:[NSArray arrayWithObjects:r, g, b, nil] withIndex:NULL];
    max = [LMFunctions maxValueInArray:[NSArray arrayWithObjects:r, g, b, nil] withIndex:NULL];
    delta = max - min;

    ret.v = max;

    if (max != 0) {
        ret.s = delta/max;
    } else {
        // r = g = b = 0, thus s = 0, v = undefined.
        ret.s = 0;
        ret.h = 0;
        ret.v = 0;
        return ret;
    }

    if (delta != 0) { // To avoid division-by-zero error.
        if (col.r == max) {
            ret.h = (col.g - col.b) / delta;        // Between yellow and magenta.
        } else if (col.g == max) {
            ret.h = 2 + (col.b - col.r) / delta;    // Between cyan and yellow.
        } else {
            ret.h = 4 + (col.r - col.g) / delta;    // Between magenta and cyan.
        }
        ret.h *= 60.0f; // Degrees.
        if (ret.h < 0) {
            ret.h += 360.0f;
        }
    } else {
        ret.h = 0;
    }


    ret.s *= 100.0f;
    ret.v *= 100.0f;

    return ret;
}




Download the ready-for-use source file (.m) of RGB to HSV Color space conversion

No comments:

Post a Comment