using Unosquare.Swan;
using System;
using System.Linq;
namespace Unosquare.RaspberryIO.Camera {
///
/// 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(Int32 r, Int32 g, Int32 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(Int32 r, Int32 g, Int32 b, String name) {
this.RGB = new[] { Convert.ToByte(r.Clamp(0, 255)), Convert.ToByte(g.Clamp(0, 255)), Convert.ToByte(b.Clamp(0, 255)) };
Single y = this.R * .299000f + this.G * .587000f + this.B * .114000f;
Single u = this.R * -.168736f + this.G * -.331264f + this.B * .500000f + 128f;
Single v = this.R * .500000f + this.G * -.418688f + this.B * -.081312f + 128f;
this.YUV = new Byte[] { (Byte)y.Clamp(0, 255), (Byte)u.Clamp(0, 255), (Byte)v.Clamp(0, 255) };
this.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 => this.RGB[0];
///
/// Gets the green byte.
///
public Byte G => this.RGB[1];
///
/// Gets the blue byte.
///
public Byte B => this.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(Boolean reverse) {
Byte[] data = this.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(Boolean reverse) {
Byte[] data = this.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()}";
}
}