Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Author baixin.zhao@rokid
- exports.rgb2hsv = function (rgb) {
- let R, G, B, H, S, V;
- R = (rgb >> 16) & 0xFF;
- G = (rgb >> 8) & 0xFF;
- B = rgb & 0xFF;
- const M = Math.max(R, G, B);
- const m = Math.min(R, G, B);
- V = M / 255; //range to [0, 1]
- S = M === 0 ? 0 : (1 - m / M);
- const num = R - 0.5 * G - 0.5 * B;
- const den = Math.sqrt(Math.pow(R, 2) + Math.pow(G, 2) + Math.pow(B, 2) - R * G - R * B - G * B);
- let div;
- if(den === 0) {
- div = 0;
- } else {
- div = num / den;
- }
- const count = Math.acos(div) / Math.PI * 180;
- if (G >= B) {
- H = count;
- } else {
- H = 360 - count;
- }
- return [H, S, V]
- };
- exports.hsv2rgb = function (hsv) {
- let R, G, B;
- let H = hsv[0];
- let S = hsv[1];
- let V = hsv[2];
- if (H === 0) {
- R = V + 2 * V * S;
- G = V - V * S;
- B = V - V * S;
- } else if (0 < H < 120) {
- R = V + V * S * Math.cos(H) / Math.cos(60 - H);
- G = V + V * S * (1 - Math.cos(H) / Math.cos(60 - H));
- B = V - V * S;
- } else if (H === 120) {
- R = V - V * S;
- G = V + 2 * V * S;
- B = V - V * S;
- } else if (120 < H < 240) {
- R = V - V * S;
- G = V + V * S * Math.cos(H - 120) / Math.cos(180 - H);
- B = V + V * S * (1 - Math.cos(H - 120) / Math.cos(180 - H));
- } else if (H === 240) {
- R = V - V * S;
- G = V - V * S;
- B = V + 2 * V * S;
- } else {
- R = V + V * S * (1 - Math.cos(H - 240) / Math.cos(300 - H));
- G = V - V * S;
- B = V + V * S * Math.cos(H - 240) / Math.cos(300 - H);
- }
- return [R, G, B]
- };
- exports.hsv2rgbw = function (hsv) {
- let r, g, b, w;
- let cos_h, cos_1047_h;
- let H = hsv[0];
- let S = hsv[1];
- let V = hsv[2];
- H = 3.14159 * H / 180; // Convert to radians.
- S = S > 0 ? (S < 1 ? S : 1) : 0; // clamp S and I to interval [0,1]
- V = V > 0 ? (V < 1 ? V : 1) : 0;
- if (H < 2.09439) {
- cos_h = Math.cos(H);
- cos_1047_h = Math.cos(1.047196667 - H);
- r = S * 255 * V / 3 * (1 + cos_h / cos_1047_h);
- g = S * 255 * V / 3 * (1 + (1 - cos_h / cos_1047_h));
- b = 0;
- w = 255 * (1 - S) * V;
- } else if (H < 4.188787) {
- H = H - 2.09439;
- cos_h = Math.cos(H);
- cos_1047_h = Math.cos(1.047196667 - H);
- g = S * 255 * V / 3 * (1 + cos_h / cos_1047_h);
- b = S * 255 * V / 3 * (1 + (1 - cos_h / cos_1047_h));
- r = 0;
- w = 255 * (1 - S) * V;
- } else {
- H = H - 4.188787;
- cos_h = Math.cos(H);
- cos_1047_h = Math.cos(1.047196667 - H);
- b = S * 255 * V / 3 * (1 + cos_h / cos_1047_h);
- r = S * 255 * V / 3 * (1 + (1 - cos_h / cos_1047_h));
- g = 0;
- w = 255 * (1 - S) * V;
- }
- return [w, r, g, b]
- };
- exports.toNum = function (arr) {
- let length = arr.length;
- let result = 0;
- arr.forEach((item, index) => {
- result += Math.round(item) * Math.pow(2, (length - 1 - index) * 8);
- });
- return result;
- };
Add Comment
Please, Sign In to add comment