ESPHome 2026.3.0-dev
Loading...
Searching...
No Matches
colorconv.h
Go to the documentation of this file.
1#pragma once
2
3#include <cstdint>
4#include <algorithm>
6
7/* Utility for converting internal \a Color RGB representation to supported IC hardware color keys
8 *
9 * Focus in driver layer is on efficiency.
10 * For optimum output quality on RGB inputs consider offline color keying/dithering.
11 * Also see e.g. Image component.
12 */
13
15
17static constexpr uint8_t COLORCONV_GRAY_THRESHOLD = 50;
18
30template<typename NATIVE_COLOR>
31constexpr NATIVE_COLOR color_to_bwyr(Color color, NATIVE_COLOR hw_black, NATIVE_COLOR hw_white, NATIVE_COLOR hw_yellow,
32 NATIVE_COLOR hw_red) {
33 // --- Step 1: Check for Grayscale (Black or White) ---
34 // We define "grayscale" as a color where the min and max components
35 // are close to each other.
36
37 const auto [min_rgb, max_rgb] = std::minmax({color.r, color.g, color.b});
38
39 if ((max_rgb - min_rgb) < COLORCONV_GRAY_THRESHOLD) {
40 // It's a shade of gray. Map to BLACK or WHITE.
41 // We split the luminance at the halfway point (382 = (255*3)/2)
42 if ((static_cast<int>(color.r) + color.g + color.b) > 382) {
43 return hw_white;
44 }
45 return hw_black;
46 }
47
48 // --- Step 2: Check for Primary/Secondary Colors ---
49 // If it's not gray, it's a color. We check which components are
50 // "on" (over 128) vs "off". This divides the RGB cube into 8 corners.
51 const bool r_on = (color.r > 128);
52 const bool g_on = (color.g > 128);
53 const bool b_on = (color.b > 128);
54
55 if (r_on) {
56 if (!b_on) {
57 return g_on ? hw_yellow : hw_red;
58 }
59
60 // At least red+blue high (but not gray) -> White
61 return hw_white;
62 } else {
63 return (b_on && g_on) ? hw_white : hw_black;
64 }
65}
66
67} // namespace esphome::epaper_spi
constexpr NATIVE_COLOR color_to_bwyr(Color color, NATIVE_COLOR hw_black, NATIVE_COLOR hw_white, NATIVE_COLOR hw_yellow, NATIVE_COLOR hw_red)
Map RGB color to discrete BWYR hex 4 color key.
Definition colorconv.h:31
uint8_t g
Definition color.h:34
uint8_t b
Definition color.h:38
uint8_t r
Definition color.h:30