A comprehensive guide to YCbCr - a digital color space that separates luminance (Y) from chrominance (Cb, Cr) components, widely used in digital video compression, JPEG images, and broadcast television for efficient color encoding and transmission.
YCbCr is a family of color spaces used in digital video and image compression systems. It separates the luminance (brightness) component Y from the chrominance (color) components Cb and Cr, taking advantage of human visual perception which is more sensitive to brightness than color information. This separation enables efficient compression and processing in digital imaging applications.
YCbCr consists of three components that represent different aspects of color information:
// Comprehensive YCbCr color space processor
class YCbCrProcessor {
constructor() {
this.standards = {
'bt601': {
name: 'ITU-R BT.601 (SDTV)',
kr: 0.299,
kg: 0.587,
kb: 0.114,
range: 'limited' // 16-235 for Y, 16-240 for Cb/Cr
},
'bt709': {
name: 'ITU-R BT.709 (HDTV)',
kr: 0.2126,
kg: 0.7152,
kb: 0.0722,
range: 'limited'
},
'bt2020': {
name: 'ITU-R BT.2020 (UHDTV)',
kr: 0.2627,
kg: 0.6780,
kb: 0.0593,
range: 'limited'
},
'jpeg': {
name: 'JPEG/JFIF',
kr: 0.299,
kg: 0.587,
kb: 0.114,
range: 'full' // 0-255 for all components
}
};
}
// Convert RGB to YCbCr using specified standard
rgbToYCbCr(r, g, b, standard = 'bt709', inputRange = 'full') {
const config = this.standards[standard];
if (!config) {
throw new Error(`Unknown YCbCr standard: ${standard}`);
}
// Normalize RGB values to 0-1 range
let rNorm, gNorm, bNorm;
if (inputRange === 'full') {
rNorm = r / 255;
gNorm = g / 255;
bNorm = b / 255;
} else {
// Limited range RGB (16-235)
rNorm = Math.max(0, (r - 16) / 219);
gNorm = Math.max(0, (g - 16) / 219);
bNorm = Math.max(0, (b - 16) / 219);
}
// Calculate Y (luminance)
const y = config.kr * rNorm + config.kg * gNorm + config.kb * bNorm;
// Calculate Cb and Cr (chrominance)
const cb = 0.5 * (bNorm - y) / (1 - config.kb);
const cr = 0.5 * (rNorm - y) / (1 - config.kr);
// Apply range scaling
let yOut, cbOut, crOut;
if (config.range === 'limited') {
yOut = Math.round(16 + y * 219);
cbOut = Math.round(128 + cb * 224);
crOut = Math.round(128 + cr * 224);
} else {
yOut = Math.round(y * 255);
cbOut = Math.round(128 + cb * 255);
crOut = Math.round(128 + cr * 255);
}
return {
y: Math.max(0, Math.min(255, yOut)),
cb: Math.max(0, Math.min(255, cbOut)),
cr: Math.max(0, Math.min(255, crOut)),
standard,
range: config.range
};
}
// Convert YCbCr to RGB using specified standard
ycbcrToRgb(y, cb, cr, standard = 'bt709', outputRange = 'full') {
const config = this.standards[standard];
if (!config) {
throw new Error(`Unknown YCbCr standard: ${standard}`);
}
// Normalize YCbCr values
let yNorm, cbNorm, crNorm;
if (config.range === 'limited') {
yNorm = Math.max(0, (y - 16) / 219);
cbNorm = (cb - 128) / 224;
crNorm = (cr - 128) / 224;
} else {
yNorm = y / 255;
cbNorm = (cb - 128) / 255;
crNorm = (cr - 128) / 255;
}
// Convert to RGB
const r = yNorm + crNorm * 2 * (1 - config.kr);
const g = yNorm - cbNorm * 2 * config.kb * (1 - config.kb) / config.kg - crNorm * 2 * config.kr * (1 - config.kr) / config.kg;
const b = yNorm + cbNorm * 2 * (1 - config.kb);
// Apply output range scaling
let rOut, gOut, bOut;
if (outputRange === 'full') {
rOut = Math.round(r * 255);
gOut = Math.round(g * 255);
bOut = Math.round(b * 255);
} else {
// Limited range RGB (16-235)
rOut = Math.round(16 + r * 219);
gOut = Math.round(16 + g * 219);
bOut = Math.round(16 + b * 219);
}
return {
r: Math.max(0, Math.min(255, rOut)),
g: Math.max(0, Math.min(255, gOut)),
b: Math.max(0, Math.min(255, bOut)),
standard,
range: outputRange
};
}
// Convert entire image from RGB to YCbCr
convertImageRgbToYCbCr(imageData, standard = 'bt709') {
const { data, width, height } = imageData;
const yChannel = new Uint8ClampedArray(width * height);
const cbChannel = new Uint8ClampedArray(width * height);
const crChannel = new Uint8ClampedArray(width * height);
for (let i = 0; i < data.length; i += 4) {
const r = data[i];
const g = data[i + 1];
const b = data[i + 2];
const pixelIndex = i / 4;
const ycbcr = this.rgbToYCbCr(r, g, b, standard);
yChannel[pixelIndex] = ycbcr.y;
cbChannel[pixelIndex] = ycbcr.cb;
crChannel[pixelIndex] = ycbcr.cr;
}
return {
y: yChannel,
cb: cbChannel,
cr: crChannel,
width,
height,
standard
};
}
// Convert YCbCr channels back to RGB image
convertYCbCrToImageRgb(ycbcrChannels) {
const { y, cb, cr, width, height, standard } = ycbcrChannels;
const result = new Uint8ClampedArray(width * height * 4);
for (let i = 0; i < y.length; i++) {
const rgb = this.ycbcrToRgb(y[i], cb[i], cr[i], standard);
const pixelIndex = i * 4;
result[pixelIndex] = rgb.r;
result[pixelIndex + 1] = rgb.g;
result[pixelIndex + 2] = rgb.b;
result[pixelIndex + 3] = 255; // Alpha
}
return new ImageData(result, width, height);
}
// Apply chroma subsampling (4:2:0, 4:2:2, 4:4:4)
applyChromaSubsampling(ycbcrChannels, subsamplingFormat = '4:2:0') {
const { y, cb, cr, width, height, standard } = ycbcrChannels;
let subsampledCb, subsampledCr, chromaWidth, chromaHeight;
switch (subsamplingFormat) {
case '4:4:4':
// No subsampling
return ycbcrChannels;
case '4:2:2':
// Horizontal subsampling by 2
chromaWidth = Math.ceil(width / 2);
chromaHeight = height;
subsampledCb = new Uint8ClampedArray(chromaWidth * chromaHeight);
subsampledCr = new Uint8ClampedArray(chromaWidth * chromaHeight);
for (let y_pos = 0; y_pos < height; y_pos++) {
for (let x_pos = 0; x_pos < chromaWidth; x_pos++) {
const srcIndex1 = y_pos * width + (x_pos * 2);
const srcIndex2 = y_pos * width + Math.min(x_pos * 2 + 1, width - 1);
const dstIndex = y_pos * chromaWidth + x_pos;
// Average two horizontal pixels
subsampledCb[dstIndex] = Math.round((cb[srcIndex1] + cb[srcIndex2]) / 2);
subsampledCr[dstIndex] = Math.round((cr[srcIndex1] + cr[srcIndex2]) / 2);
}
}
break;
case '4:2:0':
// Horizontal and vertical subsampling by 2
chromaWidth = Math.ceil(width / 2);
chromaHeight = Math.ceil(height / 2);
subsampledCb = new Uint8ClampedArray(chromaWidth * chromaHeight);
subsampledCr = new Uint8ClampedArray(chromaWidth * chromaHeight);
for (let y_pos = 0; y_pos < chromaHeight; y_pos++) {
for (let x_pos = 0; x_pos < chromaWidth; x_pos++) {
// Sample 2x2 block
const srcY1 = y_pos * 2;
const srcY2 = Math.min(y_pos * 2 + 1, height - 1);
const srcX1 = x_pos * 2;
const srcX2 = Math.min(x_pos * 2 + 1, width - 1);
const idx1 = srcY1 * width + srcX1;
const idx2 = srcY1 * width + srcX2;
const idx3 = srcY2 * width + srcX1;
const idx4 = srcY2 * width + srcX2;
const dstIndex = y_pos * chromaWidth + x_pos;
// Average 2x2 block
subsampledCb[dstIndex] = Math.round((cb[idx1] + cb[idx2] + cb[idx3] + cb[idx4]) / 4);
subsampledCr[dstIndex] = Math.round((cr[idx1] + cr[idx2] + cr[idx3] + cr[idx4]) / 4);
}
}
break;
default:
throw new Error(`Unknown subsampling format: ${subsamplingFormat}`);
}
return {
y, // Luminance always full resolution
cb: subsampledCb,
cr: subsampledCr,
width,
height,
chromaWidth,
chromaHeight,
subsamplingFormat,
standard
};
}
// Upsample chroma channels back to full resolution
upsampleChroma(subsampledChannels) {
const {
y, cb, cr, width, height,
chromaWidth, chromaHeight, subsamplingFormat, standard
} = subsampledChannels;
if (subsamplingFormat === '4:4:4') {
return subsampledChannels;
}
const fullCb = new Uint8ClampedArray(width * height);
const fullCr = new Uint8ClampedArray(width * height);
// Bilinear interpolation for upsampling
for (let y_pos = 0; y_pos < height; y_pos++) {
for (let x_pos = 0; x_pos < width; x_pos++) {
const dstIndex = y_pos * width + x_pos;
// Map to chroma coordinates
const chromaX = (x_pos / width) * chromaWidth;
const chromaY = (y_pos / height) * chromaHeight;
// Bilinear interpolation
const x1 = Math.floor(chromaX);
const y1 = Math.floor(chromaY);
const x2 = Math.min(x1 + 1, chromaWidth - 1);
const y2 = Math.min(y1 + 1, chromaHeight - 1);
const fx = chromaX - x1;
const fy = chromaY - y1;
const idx11 = y1 * chromaWidth + x1;
const idx12 = y1 * chromaWidth + x2;
const idx21 = y2 * chromaWidth + x1;
const idx22 = y2 * chromaWidth + x2;
// Interpolate Cb
const cb11 = cb[idx11], cb12 = cb[idx12], cb21 = cb[idx21], cb22 = cb[idx22];
const cbTop = cb11 * (1 - fx) + cb12 * fx;
const cbBottom = cb21 * (1 - fx) + cb22 * fx;
fullCb[dstIndex] = Math.round(cbTop * (1 - fy) + cbBottom * fy);
// Interpolate Cr
const cr11 = cr[idx11], cr12 = cr[idx12], cr21 = cr[idx21], cr22 = cr[idx22];
const crTop = cr11 * (1 - fx) + cr12 * fx;
const crBottom = cr21 * (1 - fx) + cr22 * fx;
fullCr[dstIndex] = Math.round(crTop * (1 - fy) + crBottom * fy);
}
}
return {
y,
cb: fullCb,
cr: fullCr,
width,
height,
standard
};
}
// Analyze YCbCr color distribution
analyzeYCbCrDistribution(ycbcrChannels) {
const { y, cb, cr } = ycbcrChannels;
const yStats = this.calculateChannelStatistics(y, 'Y (Luminance)');
const cbStats = this.calculateChannelStatistics(cb, 'Cb (Blue-difference)');
const crStats = this.calculateChannelStatistics(cr, 'Cr (Red-difference)');
return {
luminance: yStats,
chrominanceBlue: cbStats,
chrominanceRed: crStats,
colorfulness: this.calculateColorfulness(cb, cr),
dynamicRange: yStats.max - yStats.min,
recommendations: this.generateOptimizationRecommendations(yStats, cbStats, crStats)
};
}
calculateChannelStatistics(channel, name) {
const values = Array.from(channel);
values.sort((a, b) => a - b);
const sum = values.reduce((acc, val) => acc + val, 0);
const mean = sum / values.length;
const variance = values.reduce((acc, val) => acc + Math.pow(val - mean, 2), 0) / values.length;
const stdDev = Math.sqrt(variance);
return {
name,
min: values[0],
max: values[values.length - 1],
mean: Math.round(mean * 100) / 100,
median: values[Math.floor(values.length / 2)],
standardDeviation: Math.round(stdDev * 100) / 100,
percentile95: values[Math.floor(values.length * 0.95)],
percentile5: values[Math.floor(values.length * 0.05)]
};
}
calculateColorfulness(cb, cr) {
let colorfulness = 0;
const centerCb = 128;
const centerCr = 128;
for (let i = 0; i < cb.length; i++) {
const cbDiff = cb[i] - centerCb;
const crDiff = cr[i] - centerCr;
colorfulness += Math.sqrt(cbDiff * cbDiff + crDiff * crDiff);
}
return colorfulness / cb.length;
}
generateOptimizationRecommendations(yStats, cbStats, crStats) {
const recommendations = [];
// Check luminance distribution
if (yStats.standardDeviation < 20) {
recommendations.push('Low contrast image - consider histogram equalization');
}
if (yStats.mean < 50) {
recommendations.push('Dark image - may benefit from exposure adjustment');
} else if (yStats.mean > 200) {
recommendations.push('Bright image - check for clipping in highlights');
}
// Check chrominance utilization
const cbRange = cbStats.max - cbStats.min;
const crRange = crStats.max - crStats.min;
if (cbRange < 50 && crRange < 50) {
recommendations.push('Low color saturation - image appears desaturated');
}
// Check for potential compression artifacts
if (yStats.standardDeviation > 60) {
recommendations.push('High luminance variation - check for noise or compression artifacts');
}
return recommendations;
}
}// YCbCr processing for video compression and broadcast
class VideoYCbCrProcessor extends YCbCrProcessor {
constructor() {
super();
this.videoStandards = {
'ntsc': { standard: 'bt601', frameRate: 29.97, resolution: '720x480' },
'pal': { standard: 'bt601', frameRate: 25, resolution: '720x576' },
'hdtv': { standard: 'bt709', frameRate: 59.94, resolution: '1920x1080' },
'uhdtv': { standard: 'bt2020', frameRate: 59.94, resolution: '3840x2160' }
};
}
// Process video frame for compression
processVideoFrame(frameData, videoStandard = 'hdtv', compressionLevel = 'medium') {
const config = this.videoStandards[videoStandard];
if (!config) {
throw new Error(`Unknown video standard: ${videoStandard}`);
}
// Convert to YCbCr
const ycbcrChannels = this.convertImageRgbToYCbCr(frameData, config.standard);
// Apply chroma subsampling based on compression level
const subsamplingFormat = this.getSubsamplingFormat(compressionLevel);
const subsampled = this.applyChromaSubsampling(ycbcrChannels, subsamplingFormat);
// Apply quantization for compression
const quantized = this.applyQuantization(subsampled, compressionLevel);
return {
processedChannels: quantized,
videoStandard,
compressionLevel,
subsamplingFormat,
compressionRatio: this.calculateCompressionRatio(ycbcrChannels, quantized)
};
}
getSubsamplingFormat(compressionLevel) {
switch (compressionLevel) {
case 'low': return '4:4:4';
case 'medium': return '4:2:2';
case 'high': return '4:2:0';
default: return '4:2:2';
}
}
applyQuantization(ycbcrChannels, compressionLevel) {
const { y, cb, cr } = ycbcrChannels;
// Different quantization levels for Y vs Cb/Cr
const quantizationLevels = {
low: { y: 2, chroma: 4 },
medium: { y: 4, chroma: 8 },
high: { y: 8, chroma: 16 }
};
const levels = quantizationLevels[compressionLevel] || quantizationLevels.medium;
const quantizedY = this.quantizeChannel(y, levels.y);
const quantizedCb = this.quantizeChannel(cb, levels.chroma);
const quantizedCr = this.quantizeChannel(cr, levels.chroma);
return {
...ycbcrChannels,
y: quantizedY,
cb: quantizedCb,
cr: quantizedCr,
quantization: levels
};
}
quantizeChannel(channel, quantizationStep) {
const quantized = new Uint8ClampedArray(channel.length);
for (let i = 0; i < channel.length; i++) {
const quantizedValue = Math.round(channel[i] / quantizationStep) * quantizationStep;
quantized[i] = Math.max(0, Math.min(255, quantizedValue));
}
return quantized;
}
calculateCompressionRatio(original, compressed) {
// Simplified compression ratio calculation
const originalSize = original.y.length * 3; // RGB equivalent
let compressedSize = compressed.y.length; // Y channel full size
if (compressed.chromaWidth && compressed.chromaHeight) {
compressedSize += compressed.cb.length + compressed.cr.length;
} else {
compressedSize += compressed.cb.length + compressed.cr.length;
}
return originalSize / compressedSize;
}
}Explore these comprehensive pillar articles related to YCbCr
A comprehensive guide to color theory, its fundamental principles, and practical applications in digital design and web development.
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.
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 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.
Discover more about YCbCr and related color theory concepts
A comprehensive guide to color theory, its fundamental principles, and practical applications in digital design and web development.
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.
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.
Discover more color terminology and concepts in our comprehensive glossary.
Browse Full Glossary