Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Complexity of color::is_dark(self: ARGB) #41

Open
ListeriaM opened this issue Mar 10, 2023 · 0 comments
Open

Complexity of color::is_dark(self: ARGB) #41

ListeriaM opened this issue Mar 10, 2023 · 0 comments

Comments

@ListeriaM
Copy link

ListeriaM commented Mar 10, 2023

for $c_1 \lt c_2$ the following holds:

$\sqrt{(x - c_1)^2} \lt \sqrt{(x - c_2)^2} \iff 2 \times x \lt c_2 + c_1$

proof:

$\sqrt{(x - c_1)^2} \lt \sqrt{(x - c_2)^2}$
$(x - c_1)^2 \lt (x - c_2)^2$
$x^2 - 2 \times c_1 \times x + c_1^2 \lt x^2 - 2 \times c_2 \times x + c_2^2$
$2 \times (c_2 - c_1) \times x \lt c_2^2 - c_1^2$
$2 \times x \lt c_2 + c_1$

using the fact that $W_r - B_r = W_g - B_g = W_b - B_b$ the same logic can
be applied to r, g, b, (B)lack and (W)hite, which gives us:

$\sqrt{(r - B_r)^2 + (g - B_g)^2 + (b - B_b)^2} \lt \sqrt{(r - W_r)^2 + (g - W_g)^2 + (b - W_b)^2} \iff$
$\iff 2 \times (r + g + b) \lt (W_r + B_r) + (W_g + B_g) + (W_b + B_b)$

with the following possible implementation for color::is_dark(self: ARGB):

pub fn is_dark(self) -> bool {
    // should cast to a larger integer type to avoid overflow
    2 * (self.r + self.g + self.b)
        < (Self::WHITE.r + Self::BLACK.r)
            + (Self::WHITE.g + Self::BLACK.g)
            + (Self::WHITE.b + Self::BLACK.b)
}

considering $W_r = W_g = W_b = 255 \land B_r = B_g = B_b = 0$ we can simplify:

pub fn is_dark(self) -> bool {
    2 * (self.r as u32 + self.g as u32 + self.b as u32) < 3 * 0xff
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant