A comprehensive guide to bokeh - the aesthetic quality of out-of-focus areas in photographs, including the physics of optical blur, creative applications, and digital simulation techniques for achieving professional depth of field effects.
Bokeh (pronounced 'boh-keh') is a Japanese term meaning 'blur' or 'haze', referring to the aesthetic quality of the out-of-focus areas in a photograph. Good bokeh creates smooth, creamy backgrounds that help isolate subjects, while poor bokeh can be distracting with harsh edges or busy patterns. Bokeh quality depends on lens design, aperture shape, and optical characteristics.
Professional photo editing and enhancement tools powered by AI for photographers and content creators.
Remove backgrounds instantly • Resize without quality loss • Extract color palettes • Professional results
Bokeh occurs when light rays from out-of-focus points create circles of confusion on the sensor. The size and quality of these circles determine the bokeh character:
// Bokeh simulation and depth of field processor
class BokehProcessor {
constructor() {
this.apertureShapes = {
circular: { sides: 0, smoothness: 1.0 },
hexagonal: { sides: 6, smoothness: 0.8 },
octagonal: { sides: 8, smoothness: 0.9 },
pentagonal: { sides: 5, smoothness: 0.7 }
};
}
// Calculate circle of confusion for depth of field
calculateCircleOfConfusion(focalLength, aperture, focusDistance, subjectDistance) {
// Hyperfocal distance calculation
const hyperfocalDistance = (focalLength * focalLength) / (aperture * 0.03); // 0.03mm CoC for full frame
// Circle of confusion diameter
const cocDiameter = Math.abs(
(focalLength * focalLength * (focusDistance - subjectDistance)) /
(aperture * subjectDistance * (focusDistance - focalLength))
);
return {
diameter: cocDiameter,
hyperfocalDistance,
isInFocus: cocDiameter < 0.03, // Acceptable sharpness threshold
blurIntensity: Math.min(1, cocDiameter / 2) // Normalized blur strength
};
}
// Generate depth map from focus distance and scene geometry
generateDepthMap(sceneData, cameraSettings) {
const { focalLength, aperture, focusDistance } = cameraSettings;
const { width, height, depthBuffer } = sceneData;
const depthMap = new Float32Array(width * height);
for (let i = 0; i < depthBuffer.length; i++) {
const subjectDistance = depthBuffer[i];
const coc = this.calculateCircleOfConfusion(
focalLength, aperture, focusDistance, subjectDistance
);
depthMap[i] = coc.blurIntensity;
}
return depthMap;
}
// Apply bokeh blur to image based on depth map
applyBokehBlur(imageData, depthMap, apertureShape = 'circular', quality = 'high') {
const { data, width, height } = imageData;
const result = new Uint8ClampedArray(data.length);
const maxRadius = quality === 'high' ? 50 : quality === 'medium' ? 25 : 12;
const samples = quality === 'high' ? 64 : quality === 'medium' ? 32 : 16;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const pixelIndex = (y * width + x) * 4;
const depthIndex = y * width + x;
const blurRadius = depthMap[depthIndex] * maxRadius;
if (blurRadius < 1) {
// Sharp pixel, copy directly
result[pixelIndex] = data[pixelIndex];
result[pixelIndex + 1] = data[pixelIndex + 1];
result[pixelIndex + 2] = data[pixelIndex + 2];
result[pixelIndex + 3] = data[pixelIndex + 3];
} else {
// Apply bokeh blur
const blurred = this.sampleBokehKernel(
data, width, height, x, y, blurRadius, apertureShape, samples
);
result[pixelIndex] = blurred.r;
result[pixelIndex + 1] = blurred.g;
result[pixelIndex + 2] = blurred.b;
result[pixelIndex + 3] = data[pixelIndex + 3];
}
}
}
return new ImageData(result, width, height);
}
sampleBokehKernel(data, width, height, centerX, centerY, radius, shape, samples) {
let rSum = 0, gSum = 0, bSum = 0, weightSum = 0;
// Generate sampling points based on aperture shape
const samplePoints = this.generateApertureSamples(radius, shape, samples);
for (const point of samplePoints) {
const sampleX = Math.round(centerX + point.x);
const sampleY = Math.round(centerY + point.y);
if (sampleX >= 0 && sampleX < width && sampleY >= 0 && sampleY < height) {
const sampleIndex = (sampleY * width + sampleX) * 4;
const weight = point.weight;
rSum += data[sampleIndex] * weight;
gSum += data[sampleIndex + 1] * weight;
bSum += data[sampleIndex + 2] * weight;
weightSum += weight;
}
}
return {
r: weightSum > 0 ? Math.round(rSum / weightSum) : 0,
g: weightSum > 0 ? Math.round(gSum / weightSum) : 0,
b: weightSum > 0 ? Math.round(bSum / weightSum) : 0
};
}
generateApertureSamples(radius, shape, sampleCount) {
const samples = [];
const apertureConfig = this.apertureShapes[shape] || this.apertureShapes.circular;
if (apertureConfig.sides === 0) {
// Circular aperture - uniform disc sampling
for (let i = 0; i < sampleCount; i++) {
const angle = (i / sampleCount) * 2 * Math.PI;
const r = Math.sqrt(Math.random()) * radius; // Uniform disc distribution
samples.push({
x: Math.cos(angle) * r,
y: Math.sin(angle) * r,
weight: 1
});
}
} else {
// Polygonal aperture
const sides = apertureConfig.sides;
const angleStep = (2 * Math.PI) / sides;
for (let i = 0; i < sampleCount; i++) {
const angle = (i / sampleCount) * 2 * Math.PI;
// Find distance to polygon edge at this angle
const sideAngle = Math.floor(angle / angleStep) * angleStep;
const nextSideAngle = sideAngle + angleStep;
// Interpolate between polygon vertices
const edgeDistance = radius / Math.cos((angle - sideAngle - angleStep / 2));
const r = Math.sqrt(Math.random()) * Math.min(radius, Math.abs(edgeDistance));
samples.push({
x: Math.cos(angle) * r,
y: Math.sin(angle) * r,
weight: apertureConfig.smoothness
});
}
}
return samples;
}
// Enhance bokeh highlights
enhanceBokehHighlights(imageData, depthMap, threshold = 200, enhancement = 1.5) {
const { data, width, height } = imageData;
const result = new Uint8ClampedArray(data.length);
for (let i = 0; i < data.length; i += 4) {
const pixelIndex = i / 4;
const blurAmount = depthMap[pixelIndex];
// Calculate luminance
const luminance = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];
if (luminance > threshold && blurAmount > 0.3) {
// Enhance bright out-of-focus areas
const enhancementFactor = 1 + (enhancement - 1) * blurAmount;
result[i] = Math.min(255, data[i] * enhancementFactor);
result[i + 1] = Math.min(255, data[i + 1] * enhancementFactor);
result[i + 2] = Math.min(255, data[i + 2] * enhancementFactor);
} else {
result[i] = data[i];
result[i + 1] = data[i + 1];
result[i + 2] = data[i + 2];
}
result[i + 3] = data[i + 3];
}
return new ImageData(result, width, height);
}
// Analyze bokeh quality
analyzeBokehQuality(imageData, depthMap) {
const { data, width, height } = imageData;
let totalBlurredPixels = 0;
let smoothnessScore = 0;
let contrastVariation = 0;
let highlightCount = 0;
// Analyze out-of-focus regions
for (let y = 1; y < height - 1; y++) {
for (let x = 1; x < width - 1; x++) {
const pixelIndex = (y * width + x) * 4;
const depthIndex = y * width + x;
if (depthMap[depthIndex] > 0.3) { // Significantly out of focus
totalBlurredPixels++;
// Analyze local smoothness
const localVariance = this.calculateLocalVariance(data, width, x, y);
smoothnessScore += 1 / (1 + localVariance); // Higher variance = lower smoothness
// Check for highlights
const luminance = 0.299 * data[pixelIndex] + 0.587 * data[pixelIndex + 1] + 0.114 * data[pixelIndex + 2];
if (luminance > 200) {
highlightCount++;
}
}
}
}
const averageSmoothness = totalBlurredPixels > 0 ? smoothnessScore / totalBlurredPixels : 0;
const highlightRatio = totalBlurredPixels > 0 ? highlightCount / totalBlurredPixels : 0;
return {
overallQuality: this.gradeBokehQuality(averageSmoothness),
smoothness: averageSmoothness,
highlightQuality: this.assessHighlightQuality(highlightRatio),
blurCoverage: totalBlurredPixels / (width * height),
recommendations: this.generateBokehRecommendations(averageSmoothness, highlightRatio)
};
}
calculateLocalVariance(data, width, x, y) {
const values = [];
for (let dy = -1; dy <= 1; dy++) {
for (let dx = -1; dx <= 1; dx++) {
const pixelIndex = ((y + dy) * width + (x + dx)) * 4;
const luminance = 0.299 * data[pixelIndex] + 0.587 * data[pixelIndex + 1] + 0.114 * data[pixelIndex + 2];
values.push(luminance);
}
}
const mean = values.reduce((sum, val) => sum + val, 0) / values.length;
return values.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / values.length;
}
gradeBokehQuality(smoothness) {
if (smoothness > 0.8) return 'excellent';
if (smoothness > 0.6) return 'good';
if (smoothness > 0.4) return 'fair';
return 'poor';
}
assessHighlightQuality(highlightRatio) {
if (highlightRatio > 0.1) return 'rich';
if (highlightRatio > 0.05) return 'moderate';
return 'minimal';
}
generateBokehRecommendations(smoothness, highlightRatio) {
const recommendations = [];
if (smoothness < 0.5) {
recommendations.push('Consider using wider aperture for smoother bokeh');
recommendations.push('Try different lens with better optical design');
}
if (highlightRatio < 0.03) {
recommendations.push('Add light sources or reflective elements in background');
recommendations.push('Position subject to create more separation from background');
}
if (smoothness > 0.7 && highlightRatio > 0.08) {
recommendations.push('Excellent bokeh quality achieved');
}
return recommendations;
}
}// Creative bokeh effects and custom shapes
class CreativeBokehEffects {
constructor() {
this.bokehProcessor = new BokehProcessor();
}
// Create custom bokeh shapes using templates
createShapedBokeh(imageData, depthMap, shapeTemplate) {
const { data, width, height } = imageData;
const result = new Uint8ClampedArray(data.length);
// Process each pixel
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const pixelIndex = (y * width + x) * 4;
const depthIndex = y * width + x;
const blurAmount = depthMap[depthIndex];
if (blurAmount > 0.3) {
// Apply shaped bokeh to out-of-focus areas
const shaped = this.applyShapeTemplate(
data, width, height, x, y, blurAmount * 30, shapeTemplate
);
result[pixelIndex] = shaped.r;
result[pixelIndex + 1] = shaped.g;
result[pixelIndex + 2] = shaped.b;
} else {
// Keep sharp areas unchanged
result[pixelIndex] = data[pixelIndex];
result[pixelIndex + 1] = data[pixelIndex + 1];
result[pixelIndex + 2] = data[pixelIndex + 2];
}
result[pixelIndex + 3] = data[pixelIndex + 3];
}
}
return new ImageData(result, width, height);
}
applyShapeTemplate(data, width, height, centerX, centerY, size, template) {
let rSum = 0, gSum = 0, bSum = 0, weightSum = 0;
const halfSize = Math.floor(size / 2);
for (let dy = -halfSize; dy <= halfSize; dy++) {
for (let dx = -halfSize; dx <= halfSize; dx++) {
const sampleX = centerX + dx;
const sampleY = centerY + dy;
if (sampleX >= 0 && sampleX < width && sampleY >= 0 && sampleY < height) {
// Check if point is inside shape template
const templateX = Math.floor((dx + halfSize) / size * template.width);
const templateY = Math.floor((dy + halfSize) / size * template.height);
if (templateX >= 0 && templateX < template.width &&
templateY >= 0 && templateY < template.height) {
const templateIndex = (templateY * template.width + templateX) * 4;
const alpha = template.data[templateIndex + 3] / 255;
if (alpha > 0) {
const sampleIndex = (sampleY * width + sampleX) * 4;
rSum += data[sampleIndex] * alpha;
gSum += data[sampleIndex + 1] * alpha;
bSum += data[sampleIndex + 2] * alpha;
weightSum += alpha;
}
}
}
}
}
return {
r: weightSum > 0 ? Math.round(rSum / weightSum) : 0,
g: weightSum > 0 ? Math.round(gSum / weightSum) : 0,
b: weightSum > 0 ? Math.round(bSum / weightSum) : 0
};
}
// Generate common bokeh shape templates
generateShapeTemplate(shape, size = 64) {
const canvas = new OffscreenCanvas(size, size);
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'white';
const center = size / 2;
switch (shape) {
case 'heart':
this.drawHeart(ctx, center, center, size * 0.3);
break;
case 'star':
this.drawStar(ctx, center, center, size * 0.4, 5);
break;
case 'diamond':
this.drawDiamond(ctx, center, center, size * 0.4);
break;
case 'flower':
this.drawFlower(ctx, center, center, size * 0.3, 6);
break;
default:
ctx.beginPath();
ctx.arc(center, center, size * 0.4, 0, 2 * Math.PI);
ctx.fill();
}
return ctx.getImageData(0, 0, size, size);
}
drawHeart(ctx, x, y, size) {
ctx.beginPath();
ctx.moveTo(x, y + size * 0.3);
ctx.bezierCurveTo(x, y, x - size * 0.5, y, x - size * 0.5, y + size * 0.3);
ctx.bezierCurveTo(x - size * 0.5, y + size * 0.6, x, y + size * 0.9, x, y + size);
ctx.bezierCurveTo(x, y + size * 0.9, x + size * 0.5, y + size * 0.6, x + size * 0.5, y + size * 0.3);
ctx.bezierCurveTo(x + size * 0.5, y, x, y, x, y + size * 0.3);
ctx.fill();
}
drawStar(ctx, x, y, size, points) {
const outerRadius = size;
const innerRadius = size * 0.4;
ctx.beginPath();
for (let i = 0; i < points * 2; i++) {
const angle = (i * Math.PI) / points;
const radius = i % 2 === 0 ? outerRadius : innerRadius;
const px = x + Math.cos(angle - Math.PI / 2) * radius;
const py = y + Math.sin(angle - Math.PI / 2) * radius;
if (i === 0) {
ctx.moveTo(px, py);
} else {
ctx.lineTo(px, py);
}
}
ctx.closePath();
ctx.fill();
}
drawDiamond(ctx, x, y, size) {
ctx.beginPath();
ctx.moveTo(x, y - size);
ctx.lineTo(x + size, y);
ctx.lineTo(x, y + size);
ctx.lineTo(x - size, y);
ctx.closePath();
ctx.fill();
}
drawFlower(ctx, x, y, size, petals) {
for (let i = 0; i < petals; i++) {
const angle = (i * 2 * Math.PI) / petals;
const petalX = x + Math.cos(angle) * size * 0.3;
const petalY = y + Math.sin(angle) * size * 0.3;
ctx.beginPath();
ctx.ellipse(petalX, petalY, size * 0.3, size * 0.6, angle, 0, 2 * Math.PI);
ctx.fill();
}
// Center
ctx.beginPath();
ctx.arc(x, y, size * 0.2, 0, 2 * Math.PI);
ctx.fill();
}
}Explore these comprehensive pillar articles related to Bokeh
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 Bokeh and related color theory concepts
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.
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.
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