Shinya Matsuyama / Mbed OS MF_FUJIKO_BASE

Dependencies:   libTCS34725

ColorUtil.h

Committer:
shinyamatsuyama
Date:
2019-03-16
Revision:
6:fd9d4fed9946
Parent:
0:bed71d1853ef

File content as of revision 6:fd9d4fed9946:

#pragma once

class ColorUtil {
public:
    struct RGB {
        float r;
        float g;
        float b;
        float a;
    };

    struct HSV {
        float h;
        float s;
        float v;
    };
    
    enum BALL_COLOR {
        BALL_RED = 0,
        BALL_BLUE,
        BALL_GREEN,
        BALL_YELLOW,
    };

    static HSV RGBtoHSV(RGB rgb) {
        HSV hsv;
        
        rgb.r /= 255;
        rgb.g /= 255;
        rgb.b /= 255;
        rgb.a /= 255;
        
        float max = rgb.r;
        float min = rgb.r;
        int flg = 0;
        
        if (max < rgb.g) {
            max = rgb.g;
            flg = 1;
        }
        if (max < rgb.b) {
            max = rgb.b;
            flg = 2;
        }
        
        if (min > rgb.g) min = rgb.g;
        if (min > rgb.b) min = rgb.b;
        
        if (min == max) flg = 3;
        
        switch (flg) {
            case 0:
                hsv.h = (rgb.g - rgb.b) * 0.1667 / (max - min);
                break;
            case 1:
                hsv.h = (float)(rgb.b - rgb.r) * 0.1667 / (max - min) + 0.333;
                break;
            case 2:
                hsv.h = (float)(rgb.r - rgb.g) * 0.1667 / (max - min) + 0.667;
                break;
            case 3:
                hsv.h = 0;
                break;
        }
        while (hsv.h < 0) hsv.h += 1;
        hsv.h *= 255;
        
        hsv.s = max == 0 ? 0 : (max - min) * 255 / max;
        hsv.v = max * 255;
        
        return hsv;
    }
    
    static BALL_COLOR detectBallColor(HSV hsv) {
        if (hsv.h < 20) {
            return BALL_RED;
        }
        
        if (hsv.h < 60) {
            return BALL_YELLOW;
        }
        
        if (hsv.h < 120) {
            return BALL_GREEN;
        }
        
        if (hsv.h < 200) {
            return BALL_BLUE;
        }
        
        return BALL_RED;
    }
};