Spectrum Tools provides color conversion and terminal interaction utilities. These are used internally by Spectrum but are also available for direct use:
The Spectrum_tools.Convert module provides functions to convert RGB colors to ANSI color codes with perceptual accuracy.
The Spectrum_tools.Convert.Perceptual converter uses CIE LAB color space for quantization. See How Color Quantization Works for why LAB gives better results than RGB distance.
let color = Gg.Color.v_srgb 0.8 0.3 0.2 in
(* Convert to nearest xterm-256 color *)
let ansi256_code = Spectrum_tools.Convert.Perceptual.rgb_to_ansi256 color in
(* Convert to nearest ANSI-16 basic color *)
let ansi16_code = Spectrum_tools.Convert.Perceptual.rgb_to_ansi16 colorThe lookup uses octree-based spatial indexing in LAB space. See Spectrum_palette_ppx.Palette for details on the indexing implementation.
The Spectrum_tools.Convert.Color module extends the base Color library with additional types and conversions:
(* Create color from RGB integers (0-255) *)
let red = Spectrum_tools.Convert.Color.of_rgb 255 0 0 in
(* Convert to RGBA with integer components *)
let rgba = Spectrum_tools.Convert.Color.to_rgba red in
Printf.printf "R:%d G:%d B:%d A:%f\n" rgba.r rgba.g rgba.b rgba.a;
(* Create from HSL *)
let yellow = Spectrum_tools.Convert.Color.of_hsl 60. 100. 50. in
(* Convert to HSVA *)
let hsva = Spectrum_tools.Convert.Color.to_hsva yellowThe Spectrum_tools.Query module provides functions to query xterm-compatible terminals for their current foreground and background colors.
(* Query both foreground and background *)
let colours = Spectrum_tools.Query.Xterm.get_colours Unix.stdin in
let () =
match colours.fg with
| Ok fg_color ->
let rgba = Spectrum_tools.Convert.Color.to_rgba fg_color in
Printf.printf "Foreground: RGB(%d, %d, %d)\n" rgba.r rgba.g rgba.b
| Error msg ->
Printf.printf "Failed to detect foreground: %s\n" msg
in
let () =
match colours.bg with
| Ok bg_color ->
let rgba = Spectrum_tools.Convert.Color.to_rgba bg_color in
Printf.printf "Background: RGB(%d, %d, %d)\n" rgba.r rgba.g rgba.b
| Error msg ->
Printf.printf "Failed to detect background: %s\n" msg
in
()Queries use xterm OSC (Operating System Command) sequences:
The terminal responds with colors in 48-bit RGB format: rgb:RRRR/GGGG/BBBB
Note: The query functions automatically handle terminal raw mode setup and restoration. Only xterm-compatible terminals support these queries.
Spectrum_tools.Convert Color conversion functions for terminal colors.Spectrum_tools.Query Terminal query functions for detecting current colors.The perceptual quantization algorithm is based on LAB color space nearest-neighbor search. The implementation uses the Gg library for color space conversions and the oktree package for spatial indexing.