A comprehensive guide to luminance - the photometric measure of luminous intensity per unit area, representing the perceived brightness of light and serving as a fundamental concept in color science and image processing.
Luminance is a photometric measure of the luminous intensity per unit area of light traveling in a given direction. It represents the perceived brightness of a surface or light source and is fundamental to color science, display technology, and image processing. Luminance is measured in candelas per square meter (cd/m²) or nits.
// Luminance calculation and processing system
class LuminanceProcessor {
constructor() {
this.canvas = document.createElement('canvas');
this.ctx = this.canvas.getContext('2d');
}
// Calculate luminance from RGB values
calculateLuminance(r, g, b, colorSpace = 'sRGB') {
switch (colorSpace) {
case 'sRGB':
return this.sRGBLuminance(r, g, b);
case 'linear':
return this.linearLuminance(r, g, b);
case 'rec709':
return this.rec709Luminance(r, g, b);
case 'rec2020':
return this.rec2020Luminance(r, g, b);
default:
return this.sRGBLuminance(r, g, b);
}
}
// sRGB luminance calculation (ITU-R BT.709)
sRGBLuminance(r, g, b) {
// Convert to linear space first
const rLinear = this.srgbToLinear(r / 255);
const gLinear = this.srgbToLinear(g / 255);
const bLinear = this.srgbToLinear(b / 255);
// Apply ITU-R BT.709 coefficients
return 0.2126 * rLinear + 0.7152 * gLinear + 0.0722 * bLinear;
}
// Linear RGB luminance
linearLuminance(r, g, b) {
// Assume inputs are already in linear space (0-1)
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
// Rec. 709 luminance (HDTV)
rec709Luminance(r, g, b) {
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
// Rec. 2020 luminance (UHD TV)
rec2020Luminance(r, g, b) {
return 0.2627 * r + 0.6780 * g + 0.0593 * b;
}
srgbToLinear(value) {
return value <= 0.04045 ?
value / 12.92 :
Math.pow((value + 0.055) / 1.055, 2.4);
}
linearToSrgb(value) {
return value <= 0.0031308 ?
value * 12.92 :
1.055 * Math.pow(value, 1 / 2.4) - 0.055;
}
// Generate luminance map from image
generateLuminanceMap(imageData) {
const { data, width, height } = imageData;
const luminanceData = new Float32Array(width * height);
for (let i = 0, j = 0; i < data.length; i += 4, j++) {
const r = data[i];
const g = data[i + 1];
const b = data[i + 2];
luminanceData[j] = this.calculateLuminance(r, g, b);
}
return {
data: luminanceData,
width,
height,
min: Math.min(...luminanceData),
max: Math.max(...luminanceData),
average: luminanceData.reduce((sum, val) => sum + val, 0) / luminanceData.length
};
}
// Convert luminance map to grayscale image
luminanceToGrayscale(luminanceMap) {
const { data, width, height } = luminanceMap;
const imageData = new ImageData(width, height);
const pixelData = imageData.data;
for (let i = 0; i < data.length; i++) {
const luminance = data[i];
const grayValue = Math.round(this.linearToSrgb(luminance) * 255);
const pixelIndex = i * 4;
pixelData[pixelIndex] = grayValue; // R
pixelData[pixelIndex + 1] = grayValue; // G
pixelData[pixelIndex + 2] = grayValue; // B
pixelData[pixelIndex + 3] = 255; // A
}
return imageData;
}
}// Advanced luminance processing for HDR and tone mapping
class AdvancedLuminanceProcessor {
constructor() {
this.processor = new LuminanceProcessor();
}
// Local luminance adaptation
localLuminanceAdaptation(imageData, adaptationRadius = 50) {
const { data, width, height } = imageData;
const result = new Uint8ClampedArray(data.length);
// Generate luminance map
const luminanceMap = this.processor.generateLuminanceMap(imageData);
// Apply local adaptation
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const pixelIndex = y * width + x;
const dataIndex = pixelIndex * 4;
// Calculate local average luminance
const localLuminance = this.calculateLocalLuminance(
luminanceMap, x, y, adaptationRadius
);
// Apply adaptation
const adaptationFactor = this.calculateAdaptationFactor(
luminanceMap.data[pixelIndex],
localLuminance
);
// Apply to RGB channels
result[dataIndex] = Math.max(0, Math.min(255, data[dataIndex] * adaptationFactor));
result[dataIndex + 1] = Math.max(0, Math.min(255, data[dataIndex + 1] * adaptationFactor));
result[dataIndex + 2] = Math.max(0, Math.min(255, data[dataIndex + 2] * adaptationFactor));
result[dataIndex + 3] = data[dataIndex + 3];
}
}
return new ImageData(result, width, height);
}
calculateLocalLuminance(luminanceMap, centerX, centerY, radius) {
const { data, width, height } = luminanceMap;
let sum = 0;
let count = 0;
const startX = Math.max(0, centerX - radius);
const endX = Math.min(width - 1, centerX + radius);
const startY = Math.max(0, centerY - radius);
const endY = Math.min(height - 1, centerY + radius);
for (let y = startY; y <= endY; y++) {
for (let x = startX; x <= endX; x++) {
const distance = Math.sqrt((x - centerX) ** 2 + (y - centerY) ** 2);
if (distance <= radius) {
const index = y * width + x;
sum += data[index];
count++;
}
}
}
return count > 0 ? sum / count : 0;
}
calculateAdaptationFactor(pixelLuminance, localLuminance) {
if (localLuminance === 0) return 1;
// Simple local adaptation formula
const targetLuminance = 0.18; // 18% gray
return Math.sqrt(targetLuminance / localLuminance);
}
// Luminance-based tone mapping
luminanceBasedToneMapping(imageData, method = 'reinhard', parameters = {}) {
const luminanceMap = this.processor.generateLuminanceMap(imageData);
const { data, width, height } = imageData;
const result = new Uint8ClampedArray(data.length);
for (let i = 0, j = 0; i < data.length; i += 4, j++) {
const r = this.processor.srgbToLinear(data[i] / 255);
const g = this.processor.srgbToLinear(data[i + 1] / 255);
const b = this.processor.srgbToLinear(data[i + 2] / 255);
const originalLuminance = luminanceMap.data[j];
let mappedLuminance;
switch (method) {
case 'reinhard':
mappedLuminance = this.reinhardToneMap(originalLuminance, parameters);
break;
case 'exponential':
mappedLuminance = this.exponentialToneMap(originalLuminance, parameters);
break;
case 'logarithmic':
mappedLuminance = this.logarithmicToneMap(originalLuminance, parameters);
break;
case 'aces':
mappedLuminance = this.acesToneMap(originalLuminance, parameters);
break;
default:
mappedLuminance = originalLuminance;
}
// Preserve color ratios while changing luminance
const luminanceRatio = originalLuminance > 0 ? mappedLuminance / originalLuminance : 1;
const mappedR = r * luminanceRatio;
const mappedG = g * luminanceRatio;
const mappedB = b * luminanceRatio;
result[i] = Math.max(0, Math.min(255, this.processor.linearToSrgb(mappedR) * 255));
result[i + 1] = Math.max(0, Math.min(255, this.processor.linearToSrgb(mappedG) * 255));
result[i + 2] = Math.max(0, Math.min(255, this.processor.linearToSrgb(mappedB) * 255));
result[i + 3] = data[i + 3];
}
return new ImageData(result, width, height);
}
reinhardToneMap(luminance, params = {}) {
const { whitePoint = 1.0, key = 0.18 } = params;
const scaledLuminance = luminance * key;
return scaledLuminance / (1 + scaledLuminance / (whitePoint * whitePoint));
}
exponentialToneMap(luminance, params = {}) {
const { exposure = 1.0 } = params;
return 1 - Math.exp(-luminance * exposure);
}
logarithmicToneMap(luminance, params = {}) {
const { base = 10, scale = 1.0 } = params;
return Math.log(1 + luminance * scale) / Math.log(base);
}
acesToneMap(luminance, params = {}) {
// ACES filmic tone mapping curve
const a = 2.51;
const b = 0.03;
const c = 2.43;
const d = 0.59;
const e = 0.14;
return Math.max(0, (luminance * (a * luminance + b)) / (luminance * (c * luminance + d) + e));
}
}// Luminance analysis and perceptual measurements
class LuminanceAnalyzer {
constructor() {
this.processor = new LuminanceProcessor();
}
// Calculate contrast ratio between two luminance values
calculateContrastRatio(luminance1, luminance2) {
const lighter = Math.max(luminance1, luminance2);
const darker = Math.min(luminance1, luminance2);
// Add small value to avoid division by zero
return (lighter + 0.05) / (darker + 0.05);
}
// Analyze luminance distribution
analyzeLuminanceDistribution(imageData) {
const luminanceMap = this.processor.generateLuminanceMap(imageData);
const { data } = luminanceMap;
// Sort luminance values
const sortedLuminance = [...data].sort((a, b) => a - b);
const analysis = {
min: sortedLuminance[0],
max: sortedLuminance[sortedLuminance.length - 1],
mean: data.reduce((sum, val) => sum + val, 0) / data.length,
median: sortedLuminance[Math.floor(sortedLuminance.length / 2)],
// Percentiles
p1: sortedLuminance[Math.floor(sortedLuminance.length * 0.01)],
p5: sortedLuminance[Math.floor(sortedLuminance.length * 0.05)],
p10: sortedLuminance[Math.floor(sortedLuminance.length * 0.10)],
p90: sortedLuminance[Math.floor(sortedLuminance.length * 0.90)],
p95: sortedLuminance[Math.floor(sortedLuminance.length * 0.95)],
p99: sortedLuminance[Math.floor(sortedLuminance.length * 0.99)],
// Dynamic range
dynamicRange: Math.log2(sortedLuminance[sortedLuminance.length - 1] / Math.max(sortedLuminance[0], 0.001))
};
// Calculate standard deviation
const variance = data.reduce((sum, val) => sum + Math.pow(val - analysis.mean, 2), 0) / data.length;
analysis.standardDeviation = Math.sqrt(variance);
// Generate histogram
analysis.histogram = this.generateLuminanceHistogram(data);
return analysis;
}
generateLuminanceHistogram(luminanceData, bins = 256) {
const histogram = new Array(bins).fill(0);
const max = Math.max(...luminanceData);
const min = Math.min(...luminanceData);
const range = max - min;
if (range === 0) {
histogram[0] = luminanceData.length;
return histogram;
}
for (const luminance of luminanceData) {
const normalizedValue = (luminance - min) / range;
const bin = Math.min(bins - 1, Math.floor(normalizedValue * bins));
histogram[bin]++;
}
return histogram;
}
// Calculate perceived brightness using various models
calculatePerceivedBrightness(r, g, b, model = 'CIE') {
switch (model) {
case 'CIE':
return this.processor.calculateLuminance(r, g, b);
case 'HSP':
// HSP (Highly Sensitive Panchromatic) model
return Math.sqrt(
0.299 * (r * r) +
0.587 * (g * g) +
0.114 * (b * b)
) / 255;
case 'W3C':
// W3C relative luminance
return this.processor.sRGBLuminance(r, g, b);
case 'simple':
// Simple average
return (r + g + b) / (3 * 255);
default:
return this.processor.calculateLuminance(r, g, b);
}
}
// Analyze local contrast
analyzeLocalContrast(imageData, kernelSize = 3) {
const { data, width, height } = imageData;
const luminanceMap = this.processor.generateLuminanceMap(imageData);
const contrastMap = new Float32Array(width * height);
const halfKernel = Math.floor(kernelSize / 2);
for (let y = halfKernel; y < height - halfKernel; y++) {
for (let x = halfKernel; x < width - halfKernel; x++) {
const centerIndex = y * width + x;
const centerLuminance = luminanceMap.data[centerIndex];
let minLuminance = centerLuminance;
let maxLuminance = centerLuminance;
// Examine neighborhood
for (let dy = -halfKernel; dy <= halfKernel; dy++) {
for (let dx = -halfKernel; dx <= halfKernel; dx++) {
const neighborIndex = (y + dy) * width + (x + dx);
const neighborLuminance = luminanceMap.data[neighborIndex];
minLuminance = Math.min(minLuminance, neighborLuminance);
maxLuminance = Math.max(maxLuminance, neighborLuminance);
}
}
// Calculate local contrast
const localContrast = maxLuminance > 0 ?
(maxLuminance - minLuminance) / maxLuminance : 0;
contrastMap[centerIndex] = localContrast;
}
}
return {
data: contrastMap,
width,
height,
average: contrastMap.reduce((sum, val) => sum + val, 0) / contrastMap.length,
max: Math.max(...contrastMap)
};
}
// Generate luminance-based recommendations
generateLuminanceRecommendations(analysis) {
const recommendations = [];
// Check dynamic range
if (analysis.dynamicRange < 6) {
recommendations.push({
type: 'low_dynamic_range',
message: 'Image has limited dynamic range',
suggestion: 'Consider increasing contrast or using tone mapping',
severity: 'medium'
});
}
// Check for low contrast
if (analysis.standardDeviation < 0.1) {
recommendations.push({
type: 'low_contrast',
message: 'Image appears to have low contrast',
suggestion: 'Increase contrast or adjust levels',
severity: 'medium'
});
}
// Check for overexposure
if (analysis.p95 > 0.95) {
recommendations.push({
type: 'potential_overexposure',
message: 'Highlights may be overexposed',
suggestion: 'Reduce exposure or apply highlight recovery',
severity: 'high'
});
}
// Check for underexposure
if (analysis.p5 < 0.05) {
recommendations.push({
type: 'potential_underexposure',
message: 'Shadows may be underexposed',
suggestion: 'Increase exposure or apply shadow recovery',
severity: 'high'
});
}
return recommendations;
}
}// Display luminance and HDR processing
class DisplayLuminanceProcessor {
constructor() {
this.processor = new LuminanceProcessor();
this.analyzer = new LuminanceAnalyzer();
}
// Convert between different luminance units
convertLuminanceUnits(value, fromUnit, toUnit) {
// Convert to cd/m² (nits) first
let nits;
switch (fromUnit) {
case 'nits':
case 'cd/m2':
nits = value;
break;
case 'fL': // foot-lamberts
nits = value * 3.426;
break;
case 'apostilb':
nits = value / Math.PI;
break;
case 'lambert':
nits = value * 3183;
break;
default:
nits = value;
}
// Convert from nits to target unit
switch (toUnit) {
case 'nits':
case 'cd/m2':
return nits;
case 'fL':
return nits / 3.426;
case 'apostilb':
return nits * Math.PI;
case 'lambert':
return nits / 3183;
default:
return nits;
}
}
// Map image to display luminance range
mapToDisplayRange(imageData, displaySpecs) {
const {
minLuminance = 0.1, // nits
maxLuminance = 100, // nits
gamma = 2.4,
colorSpace = 'sRGB'
} = displaySpecs;
const { data, width, height } = imageData;
const result = new Uint8ClampedArray(data.length);
// Analyze image luminance
const analysis = this.analyzer.analyzeLuminanceDistribution(imageData);
for (let i = 0; i < data.length; i += 4) {
const r = this.processor.srgbToLinear(data[i] / 255);
const g = this.processor.srgbToLinear(data[i + 1] / 255);
const b = this.processor.srgbToLinear(data[i + 2] / 255);
// Calculate current luminance
const currentLuminance = this.processor.linearLuminance(r, g, b);
// Map to display range
const normalizedLuminance = (currentLuminance - analysis.min) / (analysis.max - analysis.min);
const displayLuminance = minLuminance + normalizedLuminance * (maxLuminance - minLuminance);
// Apply gamma correction for display
const gammaCorrected = Math.pow(displayLuminance / maxLuminance, 1 / gamma);
// Preserve color ratios
const luminanceRatio = currentLuminance > 0 ? gammaCorrected / currentLuminance : 1;
result[i] = Math.max(0, Math.min(255, this.processor.linearToSrgb(r * luminanceRatio) * 255));
result[i + 1] = Math.max(0, Math.min(255, this.processor.linearToSrgb(g * luminanceRatio) * 255));
result[i + 2] = Math.max(0, Math.min(255, this.processor.linearToSrgb(b * luminanceRatio) * 255));
result[i + 3] = data[i + 3];
}
return new ImageData(result, width, height);
}
// HDR to SDR tone mapping
hdrToSdr(imageData, targetPeakNits = 100, sourcePeakNits = 1000) {
const { data, width, height } = imageData;
const result = new Uint8ClampedArray(data.length);
const scaleFactor = targetPeakNits / sourcePeakNits;
for (let i = 0; i < data.length; i += 4) {
const r = this.processor.srgbToLinear(data[i] / 255);
const g = this.processor.srgbToLinear(data[i + 1] / 255);
const b = this.processor.srgbToLinear(data[i + 2] / 255);
// Apply tone mapping
const mappedR = this.hdrToneMapChannel(r, scaleFactor);
const mappedG = this.hdrToneMapChannel(g, scaleFactor);
const mappedB = this.hdrToneMapChannel(b, scaleFactor);
result[i] = Math.max(0, Math.min(255, this.processor.linearToSrgb(mappedR) * 255));
result[i + 1] = Math.max(0, Math.min(255, this.processor.linearToSrgb(mappedG) * 255));
result[i + 2] = Math.max(0, Math.min(255, this.processor.linearToSrgb(mappedB) * 255));
result[i + 3] = data[i + 3];
}
return new ImageData(result, width, height);
}
hdrToneMapChannel(value, scaleFactor) {
// Simple HDR tone mapping with soft knee
const scaled = value * scaleFactor;
return scaled / (1 + scaled);
}
// Generate display calibration target
generateCalibrationTarget(targetLuminance = 120, patchSize = 100) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = patchSize;
canvas.height = patchSize;
// Calculate RGB values for target luminance
const targetLinear = targetLuminance / 100; // Normalize
const targetSRGB = this.processor.linearToSrgb(targetLinear);
const rgbValue = Math.round(targetSRGB * 255);
// Fill canvas with target color
ctx.fillStyle = `rgb(${rgbValue}, ${rgbValue}, ${rgbValue})`;
ctx.fillRect(0, 0, patchSize, patchSize);
return {
canvas,
targetLuminance,
rgbValue,
linearValue: targetLinear
};
}
}Explore these comprehensive pillar articles related to Luminance
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.
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 about Luminance and related color theory concepts
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.
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.
Disclosure: The links below are Amazon affiliate links. RGBmatic earns a commission from qualifying purchases at no extra cost to you.
Discover more color terminology and concepts in our comprehensive glossary.
Browse Full Glossary