Skip to content

Commit

Permalink
colorspace: add luma to RGB and update toGray method
Browse files Browse the repository at this point in the history
  • Loading branch information
arrufat committed Jan 7, 2025
1 parent eff84cc commit a60a37b
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/colorspace.zig
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,12 @@ const RgbFloat = struct {
};
}

/// Luma is the weighted average of gamma-corrected R, G, and B, based on their contribution
/// to perceived lightness. This implementation uses the the Rec. 709 for sRGB.
fn luma(self: RgbFloat) f64 {
return 0.2126 * self.r + 0.7152 * self.g + 0.0722 * self.b;
}

/// Converts the RGB color into an HSL color.
fn toHsl(self: RgbFloat) Hsl {
const min = @min(self.r, @min(self.g, self.b));
Expand Down Expand Up @@ -275,6 +281,12 @@ pub const Rgb = struct {
};
}

/// Luma is the weighted average of gamma-corrected R, G, and B, based on their contribution
/// to perceived lightness. This implementation uses the the Rec. 709 for sRGB.
pub fn luma(self: Rgb) f64 {
return self.toRgbFloat().luma();
}

/// Alpha-blends color into self.
pub fn blend(self: *Rgb, color: Rgba) void {
alphaBlend(Rgb, self, color);
Expand All @@ -285,9 +297,9 @@ pub const Rgb = struct {
return self.r == self.g and self.g == self.b;
}

/// Converts the RGB color into grayscale.
/// Converts the RGB color into grayscale using luma.
pub fn toGray(self: Rgb) u8 {
return @intFromFloat(@round(self.toHsl().l / 100 * 255));
return @intFromFloat(self.luma() * 255);
}

/// Converts the RGB color into a hex value.
Expand Down

0 comments on commit a60a37b

Please sign in to comment.