A comprehensive guide to gamma in digital imaging - the nonlinear relationship between input values and displayed brightness, covering gamma correction, encoding/decoding, and its impact on color accuracy and image quality.
Gamma is a nonlinear operation that defines the relationship between the numerical value of a pixel and its actual luminance. It's fundamental to digital imaging, affecting how images are encoded, stored, transmitted, and displayed across different devices and systems.
Gamma describes the nonlinear relationship between input signal values and output luminance. It compensates for the nonlinear response of human vision and display devices:
// Gamma correction implementation
class GammaProcessor {
constructor() {
this.standardGamma = 2.2; // sRGB standard
this.canvas = document.createElement('canvas');
this.ctx = this.canvas.getContext('2d');
}
// Apply gamma correction to a single value
applyGamma(value, gamma = this.standardGamma) {
// Normalize to 0-1 range
const normalized = value / 255;
// Apply gamma correction
const corrected = Math.pow(normalized, 1 / gamma);
// Convert back to 0-255 range
return Math.round(corrected * 255);
}
// Remove gamma correction (linearize)
removeGamma(value, gamma = this.standardGamma) {
const normalized = value / 255;
const linearized = Math.pow(normalized, gamma);
return Math.round(linearized * 255);
}
// Apply gamma correction to RGB color
applyGammaToColor(color, gamma = this.standardGamma) {
return {
r: this.applyGamma(color.r, gamma),
g: this.applyGamma(color.g, gamma),
b: this.applyGamma(color.b, gamma)
};
}
// sRGB gamma correction (more accurate)
applySRGBGamma(value) {
const normalized = value / 255;
let corrected;
if (normalized <= 0.0031308) {
corrected = 12.92 * normalized;
} else {
corrected = 1.055 * Math.pow(normalized, 1 / 2.4) - 0.055;
}
return Math.round(corrected * 255);
}
// Remove sRGB gamma correction
removeSRGBGamma(value) {
const normalized = value / 255;
let linearized;
if (normalized <= 0.04045) {
linearized = normalized / 12.92;
} else {
linearized = Math.pow((normalized + 0.055) / 1.055, 2.4);
}
return Math.round(linearized * 255);
}
// Apply gamma correction to entire image
async applyGammaToImage(imageFile, gamma = this.standardGamma) {
return new Promise((resolve) => {
const img = new Image();
img.onload = () => {
this.canvas.width = img.width;
this.canvas.height = img.height;
this.ctx.drawImage(img, 0, 0);
const imageData = this.ctx.getImageData(0, 0, img.width, img.height);
const correctedData = this.processImageData(imageData, gamma);
this.ctx.putImageData(correctedData, 0, 0);
this.canvas.toBlob((blob) => {
resolve({
blob,
gamma,
originalSize: imageFile.size,
processedSize: blob.size,
dimensions: { width: img.width, height: img.height }
});
}, 'image/png');
};
img.src = URL.createObjectURL(imageFile);
});
}
processImageData(imageData, gamma) {
const { data, width, height } = imageData;
const processed = new Uint8ClampedArray(data.length);
for (let i = 0; i < data.length; i += 4) {
// Apply gamma correction to RGB channels
processed[i] = this.applyGamma(data[i], gamma); // Red
processed[i + 1] = this.applyGamma(data[i + 1], gamma); // Green
processed[i + 2] = this.applyGamma(data[i + 2], gamma); // Blue
processed[i + 3] = data[i + 3]; // Alpha (unchanged)
}
return new ImageData(processed, width, height);
}
// Generate gamma correction lookup table
generateGammaLUT(gamma = this.standardGamma) {
const lut = new Array(256);
for (let i = 0; i < 256; i++) {
lut[i] = this.applyGamma(i, gamma);
}
return lut;
}
// Apply gamma using lookup table (faster for batch processing)
applyGammaWithLUT(imageData, gammaLUT) {
const { data, width, height } = imageData;
const processed = new Uint8ClampedArray(data.length);
for (let i = 0; i < data.length; i += 4) {
processed[i] = gammaLUT[data[i]]; // Red
processed[i + 1] = gammaLUT[data[i + 1]]; // Green
processed[i + 2] = gammaLUT[data[i + 2]]; // Blue
processed[i + 3] = data[i + 3]; // Alpha
}
return new ImageData(processed, width, height);
}
}Different display technologies have varying gamma characteristics:
// Display gamma characteristics
const displayGamma = {
CRT: {
nativeGamma: 2.5,
description: 'Cathode Ray Tube displays',
characteristics: 'Inherently nonlinear response',
correction: 'Requires gamma correction in content'
},
LCD: {
nativeGamma: 2.2,
description: 'Liquid Crystal Display',
characteristics: 'Gamma applied in processing',
correction: 'Built-in gamma correction'
},
OLED: {
nativeGamma: 2.4,
description: 'Organic Light Emitting Diode',
characteristics: 'Near-linear response with processing',
correction: 'Software gamma correction'
},
HDR: {
nativeGamma: 'Variable',
description: 'High Dynamic Range displays',
characteristics: 'PQ or HLG transfer functions',
correction: 'Advanced tone mapping'
}
};
// Display gamma measurement and adjustment
class DisplayGammaCalibrator {
constructor() {
this.testLevels = [0, 32, 64, 96, 128, 160, 192, 224, 255];
this.targetGamma = 2.2;
}
// Measure display gamma
async measureDisplayGamma(displayElement) {
const measurements = [];
for (const level of this.testLevels) {
const measurement = await this.measureGrayLevel(displayElement, level);
measurements.push({
input: level,
measured: measurement,
expected: this.calculateExpectedOutput(level, this.targetGamma)
});
}
return this.calculateGammaFromMeasurements(measurements);
}
async measureGrayLevel(displayElement, grayLevel) {
// In real implementation, this would use a colorimeter
// Simulating measurement with some variation
const ideal = this.calculateExpectedOutput(grayLevel, 2.15); // Slightly off
const noise = (Math.random() - 0.5) * 2; // ±1 variation
return Math.max(0, Math.min(255, ideal + noise));
}
calculateExpectedOutput(input, gamma) {
const normalized = input / 255;
const output = Math.pow(normalized, 1 / gamma);
return Math.round(output * 255);
}
calculateGammaFromMeasurements(measurements) {
// Use least squares fitting to determine actual gamma
let sumXY = 0, sumX2 = 0;
for (const measurement of measurements) {
if (measurement.input > 0 && measurement.measured > 0) {
const x = Math.log(measurement.input / 255);
const y = Math.log(measurement.measured / 255);
sumXY += x * y;
sumX2 += x * x;
}
}
const measuredGamma = sumXY / sumX2;
return {
measuredGamma: Math.abs(measuredGamma),
targetGamma: this.targetGamma,
deviation: Math.abs(measuredGamma - this.targetGamma),
needsCorrection: Math.abs(measuredGamma - this.targetGamma) > 0.1,
measurements
};
}
// Generate gamma correction curve
generateCorrectionCurve(measuredGamma, targetGamma) {
const correctionGamma = targetGamma / measuredGamma;
const curve = new Array(256);
for (let i = 0; i < 256; i++) {
const normalized = i / 255;
const corrected = Math.pow(normalized, correctionGamma);
curve[i] = Math.round(corrected * 255);
}
return {
curve,
correctionGamma,
description: `Correction curve for gamma ${measuredGamma.toFixed(2)} to ${targetGamma}`
};
}
}Understanding when to work in linear vs gamma-corrected space is crucial for accurate image processing:
// Linear vs gamma-corrected image processing
class LinearImageProcessor {
constructor() {
this.gammaProcessor = new GammaProcessor();
}
// Blend two images in linear space (correct)
blendImagesLinear(image1Data, image2Data, alpha = 0.5) {
const { data: data1, width, height } = image1Data;
const data2 = image2Data.data;
const result = new Uint8ClampedArray(data1.length);
for (let i = 0; i < data1.length; i += 4) {
// Convert to linear space
const r1_linear = this.gammaProcessor.removeSRGBGamma(data1[i]);
const g1_linear = this.gammaProcessor.removeSRGBGamma(data1[i + 1]);
const b1_linear = this.gammaProcessor.removeSRGBGamma(data1[i + 2]);
const r2_linear = this.gammaProcessor.removeSRGBGamma(data2[i]);
const g2_linear = this.gammaProcessor.removeSRGBGamma(data2[i + 1]);
const b2_linear = this.gammaProcessor.removeSRGBGamma(data2[i + 2]);
// Blend in linear space
const r_blended = r1_linear * (1 - alpha) + r2_linear * alpha;
const g_blended = g1_linear * (1 - alpha) + g2_linear * alpha;
const b_blended = b1_linear * (1 - alpha) + b2_linear * alpha;
// Convert back to gamma space
result[i] = this.gammaProcessor.applySRGBGamma(r_blended);
result[i + 1] = this.gammaProcessor.applySRGBGamma(g_blended);
result[i + 2] = this.gammaProcessor.applySRGBGamma(b_blended);
result[i + 3] = data1[i + 3]; // Alpha
}
return new ImageData(result, width, height);
}
// Blend in gamma space (incorrect but common)
blendImagesGamma(image1Data, image2Data, alpha = 0.5) {
const { data: data1, width, height } = image1Data;
const data2 = image2Data.data;
const result = new Uint8ClampedArray(data1.length);
for (let i = 0; i < data1.length; i += 4) {
// Direct blending in gamma space (incorrect)
result[i] = Math.round(data1[i] * (1 - alpha) + data2[i] * alpha);
result[i + 1] = Math.round(data1[i + 1] * (1 - alpha) + data2[i + 1] * alpha);
result[i + 2] = Math.round(data1[i + 2] * (1 - alpha) + data2[i + 2] * alpha);
result[i + 3] = data1[i + 3];
}
return new ImageData(result, width, height);
}
// Resize image with proper gamma handling
resizeImageLinear(imageData, newWidth, newHeight) {
const { data, width, height } = imageData;
const result = new Uint8ClampedArray(newWidth * newHeight * 4);
const scaleX = width / newWidth;
const scaleY = height / newHeight;
for (let y = 0; y < newHeight; y++) {
for (let x = 0; x < newWidth; x++) {
const srcX = x * scaleX;
const srcY = y * scaleY;
// Bilinear interpolation in linear space
const color = this.bilinearInterpolationLinear(data, width, height, srcX, srcY);
const dstIdx = (y * newWidth + x) * 4;
result[dstIdx] = color.r;
result[dstIdx + 1] = color.g;
result[dstIdx + 2] = color.b;
result[dstIdx + 3] = color.a;
}
}
return new ImageData(result, newWidth, newHeight);
}
bilinearInterpolationLinear(data, width, height, x, y) {
const x1 = Math.floor(x);
const y1 = Math.floor(y);
const x2 = Math.min(x1 + 1, width - 1);
const y2 = Math.min(y1 + 1, height - 1);
const fx = x - x1;
const fy = y - y1;
// Get four corner pixels
const p1 = this.getPixelLinear(data, width, x1, y1);
const p2 = this.getPixelLinear(data, width, x2, y1);
const p3 = this.getPixelLinear(data, width, x1, y2);
const p4 = this.getPixelLinear(data, width, x2, y2);
// Interpolate in linear space
const r = p1.r * (1 - fx) * (1 - fy) + p2.r * fx * (1 - fy) + p3.r * (1 - fx) * fy + p4.r * fx * fy;
const g = p1.g * (1 - fx) * (1 - fy) + p2.g * fx * (1 - fy) + p3.g * (1 - fx) * fy + p4.g * fx * fy;
const b = p1.b * (1 - fx) * (1 - fy) + p2.b * fx * (1 - fy) + p3.b * (1 - fx) * fy + p4.b * fx * fy;
const a = p1.a * (1 - fx) * (1 - fy) + p2.a * fx * (1 - fy) + p3.a * (1 - fx) * fy + p4.a * fx * fy;
return {
r: this.gammaProcessor.applySRGBGamma(r),
g: this.gammaProcessor.applySRGBGamma(g),
b: this.gammaProcessor.applySRGBGamma(b),
a: Math.round(a)
};
}
getPixelLinear(data, width, x, y) {
const idx = (y * width + x) * 4;
return {
r: this.gammaProcessor.removeSRGBGamma(data[idx]),
g: this.gammaProcessor.removeSRGBGamma(data[idx + 1]),
b: this.gammaProcessor.removeSRGBGamma(data[idx + 2]),
a: data[idx + 3]
};
}
}// Gamma test pattern generator
class GammaTestGenerator {
constructor() {
this.canvas = document.createElement('canvas');
this.ctx = this.canvas.getContext('2d');
}
// Generate gamma test pattern
generateGammaTestPattern(width = 400, height = 300) {
this.canvas.width = width;
this.canvas.height = height;
// Create gradient test pattern
const gradient = this.ctx.createLinearGradient(0, 0, width, 0);
// Add color stops for smooth gradient
for (let i = 0; i <= 10; i++) {
const position = i / 10;
const grayLevel = Math.round(position * 255);
gradient.addColorStop(position, `rgb(${grayLevel}, ${grayLevel}, ${grayLevel})`);
}
this.ctx.fillStyle = gradient;
this.ctx.fillRect(0, 0, width, height / 2);
// Create dithered pattern for comparison
this.generateDitheredPattern(0, height / 2, width, height / 2);
return this.canvas.toDataURL();
}
generateDitheredPattern(x, y, width, height) {
const imageData = this.ctx.createImageData(width, height);
const data = imageData.data;
for (let py = 0; py < height; py++) {
for (let px = 0; px < width; px++) {
const position = px / width;
const targetGray = position * 255;
// Simple dithering
const threshold = (px + py) % 2 === 0 ? 128 : 127;
const ditheredGray = targetGray > threshold ? 255 : 0;
const idx = (py * width + px) * 4;
data[idx] = ditheredGray; // Red
data[idx + 1] = ditheredGray; // Green
data[idx + 2] = ditheredGray; // Blue
data[idx + 3] = 255; // Alpha
}
}
this.ctx.putImageData(imageData, x, y);
}
// Generate gamma correction test
generateGammaCorrectionTest(originalGamma, targetGamma) {
const width = 600;
const height = 200;
this.canvas.width = width;
this.canvas.height = height;
// Original gamma curve
this.drawGammaCurve(0, 0, width / 2, height, originalGamma, 'Original');
// Corrected gamma curve
this.drawGammaCurve(width / 2, 0, width / 2, height, targetGamma, 'Corrected');
return this.canvas.toDataURL();
}
drawGammaCurve(x, y, width, height, gamma, label) {
this.ctx.fillStyle = '#f0f0f0';
this.ctx.fillRect(x, y, width, height);
// Draw curve
this.ctx.strokeStyle = '#333';
this.ctx.lineWidth = 2;
this.ctx.beginPath();
for (let i = 0; i <= width; i++) {
const input = i / width;
const output = Math.pow(input, 1 / gamma);
const plotX = x + i;
const plotY = y + height - (output * height);
if (i === 0) {
this.ctx.moveTo(plotX, plotY);
} else {
this.ctx.lineTo(plotX, plotY);
}
}
this.ctx.stroke();
// Draw label
this.ctx.fillStyle = '#333';
this.ctx.font = '14px Arial';
this.ctx.fillText(`${label} (γ=${gamma})`, x + 10, y + 20);
// Draw grid
this.ctx.strokeStyle = '#ccc';
this.ctx.lineWidth = 1;
// Vertical lines
for (let i = 0; i <= 4; i++) {
const gridX = x + (i * width / 4);
this.ctx.beginPath();
this.ctx.moveTo(gridX, y);
this.ctx.lineTo(gridX, y + height);
this.ctx.stroke();
}
// Horizontal lines
for (let i = 0; i <= 4; i++) {
const gridY = y + (i * height / 4);
this.ctx.beginPath();
this.ctx.moveTo(x, gridY);
this.ctx.lineTo(x + width, gridY);
this.ctx.stroke();
}
}
// Visual gamma test
generateVisualGammaTest() {
const width = 400;
const height = 400;
this.canvas.width = width;
this.canvas.height = height;
// Create checkerboard pattern at different gamma levels
const gammaLevels = [1.8, 2.0, 2.2, 2.4];
const sectionHeight = height / gammaLevels.length;
gammaLevels.forEach((gamma, index) => {
const y = index * sectionHeight;
this.drawGammaCheckerboard(0, y, width, sectionHeight, gamma);
// Label
this.ctx.fillStyle = '#fff';
this.ctx.font = '16px Arial';
this.ctx.fillText(`γ = ${gamma}`, 10, y + 25);
});
return this.canvas.toDataURL();
}
drawGammaCheckerboard(x, y, width, height, gamma) {
const checkSize = 20;
const processor = new GammaProcessor();
for (let py = 0; py < height; py += checkSize) {
for (let px = 0; px < width; px += checkSize) {
const isEven = (Math.floor(px / checkSize) + Math.floor(py / checkSize)) % 2 === 0;
const baseGray = isEven ? 128 : 127;
// Apply gamma correction
const correctedGray = processor.applyGamma(baseGray, gamma);
this.ctx.fillStyle = `rgb(${correctedGray}, ${correctedGray}, ${correctedGray})`;
this.ctx.fillRect(x + px, y + py, checkSize, checkSize);
}
}
}
}Explore these comprehensive pillar articles related to Gamma
A comprehensive guide to color theory, its fundamental principles, and practical applications in digital design and web development.
Comprehensive guide to complementary colors - opposing hues on the color wheel that create maximum visual contrast, dynamic tension, and powerful design impact through scientific color relationships and perceptual phenomena.
Comprehensive guide to analogous color schemes - adjacent hues on the color wheel that create natural harmony, visual cohesion, and sophisticated design solutions through subtle color relationships and graduated transitions.
Comprehensive guide to triadic color schemes - three colors evenly spaced around the color wheel that create balanced, vibrant, and dynamic visual compositions with mathematical precision and artistic appeal.
Discover more about Gamma and related color theory concepts
A comprehensive guide to color theory, its fundamental principles, and practical applications in digital design and web development.
Comprehensive guide to analogous color schemes - adjacent hues on the color wheel that create natural harmony, visual cohesion, and sophisticated design solutions through subtle color relationships and graduated transitions.
Comprehensive guide to complementary colors - opposing hues on the color wheel that create maximum visual contrast, dynamic tension, and powerful design impact through scientific color relationships and perceptual phenomena.
A comprehensive guide to monochromatic color schemes - sophisticated single-hue harmonies that create unified visual experiences through systematic variations in saturation, lightness, and tonal relationships, essential for elegant design compositions, brand consistency, and advanced color theory applications requiring cohesive aesthetic unity.
A comprehensive guide to split-complementary color schemes - sophisticated three-color harmonies that combine a base color with two colors adjacent to its complement, creating balanced visual contrast with reduced tension compared to direct complementary pairs, essential for refined design compositions, brand identity systems, and advanced color theory applications.
A comprehensive guide to tetradic color schemes - sophisticated four-color harmonies that use two complementary pairs arranged in rectangular or square formations on the color wheel, providing maximum color variety while maintaining structured relationships essential for dynamic design compositions, brand systems, and advanced color theory applications.
Discover more color terminology and concepts in our comprehensive glossary.
Browse Full Glossary