Integer approximation of gamma correction (brightens midtones) Uses a simple curve: out = 255 * sqrt(in/255) ≈ sqrt(in * 255)
| 15 | // Integer approximation of gamma correction (brightens midtones) |
| 16 | // Uses a simple curve: out = 255 * sqrt(in/255) ≈ sqrt(in * 255) |
| 17 | static inline int applyGamma(int gray) { |
| 18 | if (!GAMMA_CORRECTION) return gray; |
| 19 | // Fast integer square root approximation for gamma ~0.5 (brightening) |
| 20 | // This brightens dark/mid tones while preserving highlights |
| 21 | const int product = gray * 255; |
| 22 | // Newton-Raphson integer sqrt (2 iterations for good accuracy) |
| 23 | int x = gray; |
| 24 | if (x > 0) { |
| 25 | x = (x + product / x) >> 1; |
| 26 | x = (x + product / x) >> 1; |
| 27 | } |
| 28 | return x > 255 ? 255 : x; |
| 29 | } |
| 30 | |
| 31 | // Apply contrast adjustment around midpoint (128) |
| 32 | // factor > 1.0 increases contrast, < 1.0 decreases |