namespace Unosquare.RaspberryIO.Camera { using Swan; using System; using System.Linq; /// /// A simple RGB color class to represent colors in RGB and YUV colorspaces. /// public class CameraColor { /// /// Initializes a new instance of the class. /// /// The red. /// The green. /// The blue. public CameraColor(int r, int g, int b) : this(r, g, b, string.Empty) { } /// /// Initializes a new instance of the class. /// /// The red. /// The green. /// The blue. /// The well-known color name. public CameraColor(int r, int g, int b, string name) { RGB = new[] { Convert.ToByte(r.Clamp(0, 255)), Convert.ToByte(g.Clamp(0, 255)), Convert.ToByte(b.Clamp(0, 255)) }; var y = (R * .299000f) + (G * .587000f) + (B * .114000f); var u = (R * -.168736f) + (G * -.331264f) + (B * .500000f) + 128f; var v = (R * .500000f) + (G * -.418688f) + (B * -.081312f) + 128f; YUV = new byte[] { (byte)y.Clamp(0, 255), (byte)u.Clamp(0, 255), (byte)v.Clamp(0, 255) }; Name = name; } #region Static Definitions /// /// Gets the predefined white color. /// public static CameraColor White => new CameraColor(255, 255, 255, nameof(White)); /// /// Gets the predefined red color. /// public static CameraColor Red => new CameraColor(255, 0, 0, nameof(Red)); /// /// Gets the predefined green color. /// public static CameraColor Green => new CameraColor(0, 255, 0, nameof(Green)); /// /// Gets the predefined blue color. /// public static CameraColor Blue => new CameraColor(0, 0, 255, nameof(Blue)); /// /// Gets the predefined black color. /// public static CameraColor Black => new CameraColor(0, 0, 0, nameof(Black)); #endregion /// /// Gets the well-known color name. /// public string Name { get; } /// /// Gets the red byte. /// public byte R => RGB[0]; /// /// Gets the green byte. /// public byte G => RGB[1]; /// /// Gets the blue byte. /// public byte B => RGB[2]; /// /// Gets the RGB byte array (3 bytes). /// public byte[] RGB { get; } /// /// Gets the YUV byte array (3 bytes). /// public byte[] YUV { get; } /// /// Returns a hexadecimal representation of the RGB byte array. /// Preceded by 0x and all in lowercase /// /// if set to true [reverse]. /// A string public string ToRgbHex(bool reverse) { var data = RGB.ToArray(); if (reverse) Array.Reverse(data); return ToHex(data); } /// /// Returns a hexadecimal representation of the YUV byte array. /// Preceded by 0x and all in lowercase /// /// if set to true [reverse]. /// A string public string ToYuvHex(bool reverse) { var data = YUV.ToArray(); if (reverse) Array.Reverse(data); return ToHex(data); } /// /// Returns a hexadecimal representation of the data byte array /// /// The data. /// A string private static string ToHex(byte[] data) => $"0x{BitConverter.ToString(data).Replace("-", string.Empty).ToLowerInvariant()}"; } }