Skip to content

Commit

Permalink
Clamp RGB values between 0 and 1 (#25)
Browse files Browse the repository at this point in the history
Some failures are occuring due to floating point precision where very
small negative values are sticking around through XYZ->RGB
transformation. This Should correct for that by clamping the RGB values.
  • Loading branch information
llvm-beanz authored Jan 14, 2025
1 parent c9fa89b commit 0b8a107
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib/Image/Color.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ static Color multiply(const Color LHS, double Mat[9], ColorSpace NewSpace) {
return Color(X, Y, Z, NewSpace);
}

static Color clampColor(const Color C) {
return Color(std::clamp(C.R, 0.0, 1.0), std::clamp(C.G, 0.0, 1.0),
std::clamp(C.B, 0.0, 1.0), C.Space);
}

static Color RGBToXYZ(const Color Old) {
// Matrix assumes D65 white point.
// Source: http://brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
Expand All @@ -39,7 +44,7 @@ static Color XYZToRGB(const Color Old) {
// Source: http://brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
double Mat[] = {3.2404542, -1.5371385, -0.4985314, -0.9692660, 1.8760108,
0.0415560, 0.0556434, -0.2040259, 1.0572252};
return multiply(Old, Mat, ColorSpace::RGB);
return clampColor(multiply(Old, Mat, ColorSpace::RGB));
}

static double convertXYZ(double Val) {
Expand Down

0 comments on commit 0b8a107

Please sign in to comment.