diff --git a/samples/ComputeSharp.BokehBlur/ComputeSharp.BokehBlur.csproj b/samples/ComputeSharp.BokehBlur/ComputeSharp.BokehBlur.csproj index 4e012e0c..3e629c91 100644 --- a/samples/ComputeSharp.BokehBlur/ComputeSharp.BokehBlur.csproj +++ b/samples/ComputeSharp.BokehBlur/ComputeSharp.BokehBlur.csproj @@ -16,7 +16,7 @@ - + diff --git a/samples/ComputeSharp.BokehBlur/NuGet.config b/samples/ComputeSharp.BokehBlur/NuGet.config new file mode 100644 index 00000000..1e83bce6 --- /dev/null +++ b/samples/ComputeSharp.BokehBlur/NuGet.config @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/samples/ComputeSharp.BokehBlur/Processor/HlslBokehBlurProcessor.cs b/samples/ComputeSharp.BokehBlur/Processor/HlslBokehBlurProcessor.cs new file mode 100644 index 00000000..2f1899c1 --- /dev/null +++ b/samples/ComputeSharp.BokehBlur/Processor/HlslBokehBlurProcessor.cs @@ -0,0 +1,65 @@ +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Processing.Processors; + +namespace ComputeSharp.BokehBlur.Processor +{ + /// + /// Applies bokeh blur processing to the image + /// + public sealed class HlslBokehBlurProcessor : IImageProcessor + { + /// + /// The default radius used by the parameterless constructor + /// + public const int DefaultRadius = 32; + + /// + /// The default component count used by the parameterless constructor + /// + public const int DefaultComponents = 2; + + /// + /// The default gamma used by the parameterless constructor + /// + public const float DefaultGamma = 3f; + + /// + /// Initializes a new instance of the class + /// + public HlslBokehBlurProcessor() : this(DefaultRadius, DefaultComponents, DefaultGamma) { } + + /// + /// Initializes a new instance of the class + /// + /// The size of the area to sample + /// The number of components to use to approximate the original 2D bokeh blur convolution kernel + /// The gamma highlight factor to use to further process the image + public HlslBokehBlurProcessor(int radius, int components, float gamma) + { + Radius = radius; + Components = components; + Gamma = gamma; + } + + /// + /// Gets the radius + /// + public int Radius { get; } + + /// + /// Gets the number of components + /// + public int Components { get; } + + /// + /// Gets the gamma highlight factor to use when applying the effect + /// + public float Gamma { get; } + + /// + public IImageProcessor CreatePixelSpecificProcessor() where TPixel : struct, IPixel + { + return new HlslBokehBlurProcessor(this); + } + } +} diff --git a/samples/ComputeSharp.BokehBlur/Processor/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.BokehBlur/Processor/HlslBokehBlurProcessor{TPixel}.cs new file mode 100644 index 00000000..82ca2d3c --- /dev/null +++ b/samples/ComputeSharp.BokehBlur/Processor/HlslBokehBlurProcessor{TPixel}.cs @@ -0,0 +1,455 @@ +using System; +using System.Buffers; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Advanced; +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Processing.Processors; +using SixLabors.Primitives; + +namespace ComputeSharp.BokehBlur.Processor +{ + /// + /// Applies bokeh blur processing to the image + /// + /// The pixel format + /// This processor is based on the code from Mike Pound, see github.com/mikepound/convolve + public sealed class HlslBokehBlurProcessor : IImageProcessor where TPixel : struct, IPixel + { + /// + /// The kernel radius + /// + private readonly int Radius; + + /// + /// The gamma highlight factor to use when applying the effect + /// + private readonly float Gamma; + + /// + /// The maximum size of the kernel in either direction + /// + private readonly int KernelSize; + + /// + /// The number of components to use when applying the bokeh blur + /// + private readonly int ComponentsCount; + + /// + /// The kernel parameters to use for the current instance (a: X, b: Y, A: Z, B: W) + /// + private readonly Vector4[] KernelParameters; + + /// + /// The kernel components for the current instance + /// + private readonly Vector2[][] Kernels; + + /// + /// The scaling factor for kernel values + /// + private readonly float KernelsScale; + + /// + /// The mapping of initialized complex kernels and parameters, to speed up the initialization of new instances + /// + private static readonly ConcurrentDictionary<(int Radius, int ComponentsCount), (Vector4[] Parameters, float Scale, Vector2[][] Kernels)> Cache = new ConcurrentDictionary<(int, int), (Vector4[], float, Vector2[][])>(); + + /// + /// Initializes a new instance of the class + /// + /// The defining the processor parameters + public HlslBokehBlurProcessor(HlslBokehBlurProcessor definition) + { + Radius = definition.Radius; + KernelSize = Radius * 2 + 1; + ComponentsCount = definition.Components; + Gamma = definition.Gamma; + + // Reuse the initialized values from the cache, if possible + var parameters = (Radius, ComponentsCount); + if (Cache.TryGetValue(parameters, out var info)) + { + KernelParameters = info.Parameters; + KernelsScale = info.Scale; + Kernels = info.Kernels; + } + else + { + // Initialize the complex kernels and parameters with the current arguments + (KernelParameters, KernelsScale) = GetParameters(); + Kernels = CreateComplexKernels(); + NormalizeKernels(); + + // Store them in the cache for future use + Cache.TryAdd(parameters, (KernelParameters, KernelsScale, Kernels)); + } + } + + /// + /// Gets the kernel scales to adjust the component values in each kernel + /// + private static IReadOnlyList KernelScales { get; } = new[] { 1.4f, 1.2f, 1.2f, 1.2f, 1.2f, 1.2f }; + + /// + /// Gets the available bokeh blur kernel parameters + /// + private static IReadOnlyList KernelComponents { get; } = new[] + { + // 1 component + new[] { new Vector4(0.862325f, 1.624835f, 0.767583f, 1.862321f) }, + + // 2 components + new[] + { + new Vector4(0.886528f, 5.268909f, 0.411259f, -0.548794f), + new Vector4(1.960518f, 1.558213f, 0.513282f, 4.56111f) + }, + + // 3 components + new[] + { + new Vector4(2.17649f, 5.043495f, 1.621035f, -2.105439f), + new Vector4(1.019306f, 9.027613f, -0.28086f, -0.162882f), + new Vector4(2.81511f, 1.597273f, -0.366471f, 10.300301f) + }, + + // 4 components + new[] + { + new Vector4(4.338459f, 1.553635f, -5.767909f, 46.164397f), + new Vector4(3.839993f, 4.693183f, 9.795391f, -15.227561f), + new Vector4(2.791880f, 8.178137f, -3.048324f, 0.302959f), + new Vector4(1.342190f, 12.328289f, 0.010001f, 0.244650f) + }, + + // 5 components + new[] + { + new Vector4(4.892608f, 1.685979f, -22.356787f, 85.91246f), + new Vector4(4.71187f, 4.998496f, 35.918936f, -28.875618f), + new Vector4(4.052795f, 8.244168f, -13.212253f, -1.578428f), + new Vector4(2.929212f, 11.900859f, 0.507991f, 1.816328f), + new Vector4(1.512961f, 16.116382f, 0.138051f, -0.01f) + }, + + // 6 components + new[] + { + new Vector4(5.143778f, 2.079813f, -82.326596f, 111.231024f), + new Vector4(5.612426f, 6.153387f, 113.878661f, 58.004879f), + new Vector4(5.982921f, 9.802895f, 39.479083f, -162.028887f), + new Vector4(6.505167f, 11.059237f, -71.286026f, 95.027069f), + new Vector4(3.869579f, 14.81052f, 1.405746f, -3.704914f), + new Vector4(2.201904f, 19.032909f, -0.152784f, -0.107988f) + } + }; + + /// + /// Gets the kernel parameters and scaling factor for the current count value in the current instance + /// + private (Vector4[] Parameters, float Scale) GetParameters() + { + // Prepare the kernel components + int index = Math.Max(0, Math.Min(ComponentsCount - 1, KernelComponents.Count)); + return (KernelComponents[index], KernelScales[index]); + } + + /// + /// Creates the collection of complex 1D kernels with the specified parameters + /// + private Vector2[][] CreateComplexKernels() + { + var kernels = new Vector2[KernelParameters.Length][]; + ref Vector4 baseRef = ref MemoryMarshal.GetReference(KernelParameters.AsSpan()); + for (int i = 0; i < KernelParameters.Length; i++) + { + ref Vector4 paramsRef = ref Unsafe.Add(ref baseRef, i); + kernels[i] = CreateComplex1DKernel(paramsRef.X, paramsRef.Y); + } + + return kernels; + } + + /// + /// Creates a complex 1D kernel with the specified parameters + /// + /// The exponential parameter for each complex component + /// The angle component for each complex component + private Vector2[] CreateComplex1DKernel(float a, float b) + { + var kernel = new Vector2[KernelSize]; + ref Vector2 baseRef = ref MemoryMarshal.GetReference(kernel.AsSpan()); + int r = Radius, n = -r; + + for (int i = 0; i < KernelSize; i++, n++) + { + // Incrementally compute the range values + float value = n * KernelsScale * (1f / r); + value *= value; + + // Fill in the complex kernel values + Unsafe.Add(ref baseRef, i) = new Vector2( + MathF.Exp(-a * value) * MathF.Cos(b * value), + MathF.Exp(-a * value) * MathF.Sin(b * value)); + } + + return kernel; + } + + /// + /// Normalizes the kernels with respect to A * real + B * imaginary + /// + private void NormalizeKernels() + { + // Calculate the complex weighted sum + float total = 0; + Span kernelsSpan = Kernels.AsSpan(); + ref Vector2[] baseKernelsRef = ref MemoryMarshal.GetReference(kernelsSpan); + ref Vector4 baseParamsRef = ref MemoryMarshal.GetReference(KernelParameters.AsSpan()); + + for (int i = 0; i < KernelParameters.Length; i++) + { + ref Vector2[] kernelRef = ref Unsafe.Add(ref baseKernelsRef, i); + int length = kernelRef.Length; + ref Vector2 valueRef = ref kernelRef[0]; + ref Vector4 paramsRef = ref Unsafe.Add(ref baseParamsRef, i); + + for (int j = 0; j < length; j++) + { + for (int k = 0; k < length; k++) + { + ref Vector2 jRef = ref Unsafe.Add(ref valueRef, j); + ref Vector2 kRef = ref Unsafe.Add(ref valueRef, k); + total += + paramsRef.Z * (jRef.X * kRef.X - jRef.Y * kRef.Y) + + paramsRef.W * (jRef.X * kRef.Y + jRef.Y * kRef.X); + } + } + } + + // Normalize the kernels + float scalar = 1f / MathF.Sqrt(total); + for (int i = 0; i < kernelsSpan.Length; i++) + { + ref Vector2[] kernelsRef = ref Unsafe.Add(ref baseKernelsRef, i); + int length = kernelsRef.Length; + ref Vector2 valueRef = ref kernelsRef[0]; + + for (int j = 0; j < length; j++) + { + Unsafe.Add(ref valueRef, j) *= scalar; + } + } + } + + /// + public void Apply(Image source, Rectangle sourceRectangle) + { + // Preliminary gamma highlight pass + using IMemoryOwner source4 = GetExposedVector4Buffer(source); + + using ReadOnlyBuffer sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer(source4.Memory.Span); + using ReadWriteBuffer processingBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Size); + using ReadWriteBuffer firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Size * 2); + using ReadWriteBuffer secondPassBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Size * 2); + + // Perform two 1D convolutions for each component in the current instance + for (int i = 0; i < Kernels.Length; i++) + { + // Compute the resulting complex buffer for the current component + ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(Kernels[i]); + ApplyVerticalConvolution(sourceBuffer, firstPassBuffer, kernelBuffer, source.Width, source.Height); + ApplyHorizontalConvolution(firstPassBuffer, secondPassBuffer, kernelBuffer, source.Width, source.Height); + + // Add the results of the convolution with the current kernel + Vector4 parameters = KernelParameters[i]; + SumProcessingPartials(secondPassBuffer, processingBuffer, parameters.Z, parameters.W, source.Width, source.Height); + } + + // Apply the inverse gamma exposure pass, and write the final pixel data + processingBuffer.GetData(source4.Memory.Span); + ApplyInverseGammaExposure(source4, source); + } + + /// + /// Performs a vertical 1D complex convolution with the specified parameters + /// + /// The source to read data from + /// The target to write the results to + /// The with the values for the current complex kernel + /// The width of the image being processed + /// The height of the image being processed + private void ApplyVerticalConvolution( + ReadOnlyBuffer source, + ReadWriteBuffer target, + ReadOnlyBuffer kernel, + int width, int height) + { + int maxY = height - 1; + int maxX = width - 1; + int kernelLength = kernel.Size; + + Gpu.Default.For(width, height, id => + { + Vector4 real = Vector4.Zero; + Vector4 imaginary = Vector4.Zero; + int radiusY = kernelLength >> 1; + int sourceOffsetColumnBase = id.X; + + for (int i = 0; i < kernelLength; i++) + { + int offsetY = Hlsl.Clamp(id.Y + i - radiusY, 0, maxY); + int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); + Vector4 color = source[offsetY * width + offsetX]; + Vector2 factors = kernel[i]; + + real += factors.X * color; + imaginary += factors.Y * color; + } + + int offsetXY = id.Y * width * 2 + id.X * 2; + target[offsetXY] = real; + target[offsetXY + 1] = imaginary; + }); + } + + /// + /// Performs an horizontal 1D complex convolution with the specified parameters + /// + /// The source to read data from + /// The target to write the results to + /// The with the values for the current complex kernel + /// The width of the image being processed + /// The height of the image being processed + private void ApplyHorizontalConvolution( + ReadWriteBuffer source, + ReadWriteBuffer target, + ReadOnlyBuffer kernel, + int width, int height) + { + int maxY = height - 1; + int maxX = width - 1; + int kernelLength = kernel.Size; + + Gpu.Default.For(width, height, id => + { + Vector4 real = Vector4.Zero; + Vector4 imaginary = Vector4.Zero; + int radiusX = kernelLength >> 1; + int sourceOffsetColumnBase = id.X; + int offsetY = Hlsl.Clamp(id.Y, 0, maxY); + int offsetXY; + + for (int i = 0; i < kernelLength; i++) + { + int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX); + offsetXY = offsetY * width * 2 + offsetX * 2; + Vector4 sourceReal = source[offsetXY]; + Vector4 sourceImaginary = source[offsetXY + 1]; + Vector2 factors = kernel[i]; + + real += factors.X * sourceReal - factors.Y * sourceImaginary; + imaginary += factors.X * sourceImaginary + factors.Y * sourceReal; + } + + offsetXY = id.Y * width * 2 + id.X * 2; + target[offsetXY] = real; + target[offsetXY + 1] = imaginary; + }); + } + + /// + /// Applies the gamma correction/highlight to the input pixel buffer and returns an instance with values. + /// + /// The source to read + [Pure] + private IMemoryOwner GetExposedVector4Buffer(Image sourceImage) + { + IMemoryOwner source4 = sourceImage.GetConfiguration().MemoryAllocator.Allocate(sourceImage.Width * sourceImage.Height); + float exp = Gamma; + int width = sourceImage.Width; + + Parallel.For(0, sourceImage.Height, y => + { + ref TPixel rPixel = ref sourceImage.GetPixelRowSpan(y).GetPinnableReference(); + ref Vector4 r4 = ref source4.Memory.Span.Slice(y * width).GetPinnableReference(); + + for (int x = 0; x < width; x++) + { + ref Vector4 v = ref Unsafe.Add(ref r4, x); + v = Unsafe.Add(ref rPixel, x).ToVector4(); + v.X = MathF.Pow(v.X, exp); + v.Y = MathF.Pow(v.Y, exp); + v.Z = MathF.Pow(v.Z, exp); + } + }); + + return source4; + } + + /// + /// Applies the inverse gamma exposure pass to compute the final pixel values for a target image + /// + /// The source buffer to read from + /// The target instance to write to + private void ApplyInverseGammaExposure(IMemoryOwner sourceValues, Image targetImage) + { + int width = targetImage.Width; + float expGamma = 1 / Gamma; + + Parallel.For(0, targetImage.Height, y => + { + Vector4 low = Vector4.Zero; + var high = new Vector4(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); + + ref TPixel rPixel = ref targetImage.GetPixelRowSpan(y).GetPinnableReference(); + ref Vector4 r4 = ref sourceValues.Memory.Span.Slice(y * width).GetPinnableReference(); + + for (int x = 0; x < width; x++) + { + Vector4 v = Unsafe.Add(ref r4, x); + var clamp = Vector4.Clamp(v, low, high); + v.X = MathF.Pow(clamp.X, expGamma); + v.Y = MathF.Pow(clamp.Y, expGamma); + v.Z = MathF.Pow(clamp.Z, expGamma); + + Unsafe.Add(ref rPixel, x).FromVector4(v); + } + }); + } + + /// + /// Sums the partial results for a complex convolution pass over a single kernel component + /// + /// The source to read data from + /// The target to write the results to + /// The weight factor for the real component of the complex pixel values + /// The weight factor for the imaginary component of the complex pixel values + /// The width of the image being processed + /// The height of the image being processed + private void SumProcessingPartials( + ReadWriteBuffer source, + ReadWriteBuffer target, + float z, + float w, + int width, int height) + { + Gpu.Default.For(width, height, id => + { + int offsetXY = id.Y * width * 2 + id.X * 2; + Vector4 real = source[offsetXY]; + Vector4 imaginary = source[offsetXY + 1]; + + target[id.Y * width + id.X] += real * z + imaginary * w; + }); + } + } +} diff --git a/samples/ComputeSharp.BokehBlur/Program.cs b/samples/ComputeSharp.BokehBlur/Program.cs index 5b0fae6f..4c970cb4 100644 --- a/samples/ComputeSharp.BokehBlur/Program.cs +++ b/samples/ComputeSharp.BokehBlur/Program.cs @@ -1,142 +1,24 @@ using System; using System.IO; using System.Reflection; -using System.Runtime.CompilerServices; -using System.Threading.Tasks; +using ComputeSharp.BokehBlur.Processor; using SixLabors.ImageSharp; -using SixLabors.ImageSharp.Advanced; using SixLabors.ImageSharp.PixelFormats; -using Vector4 = System.Numerics.Vector4; +using SixLabors.ImageSharp.Processing; namespace ComputeSharp.BokehBlur { class Program { - /// - /// The radius of the bokeh blur effect to apply - /// - private const int Radius = 48; - - /// - /// The gamma exposure value to use when applying the effect - /// - private const float Gamma = 3; - - /// - /// The inverse gamma exposure value to use when applying the effect - /// - private const float InverseGamma = 1 / Gamma; - static void Main() { - // Load the input image Console.WriteLine(">> Loading image"); string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "city.jpg"); - using Image image = Image.Load(path); - var (height, width) = (image.Height, image.Width); + using Image image = Image.Load(path); - // Get the vector buffer - Console.WriteLine(">> Getting pixel data"); - Vector4[] vectorArray = new Vector4[height * width]; + Console.WriteLine(">> Applying blur"); + image.Mutate(c => c.ApplyProcessor(new HlslBokehBlurProcessor(80, 2, 3))); - // Populate the buffer - Parallel.For(0, height, i => - { - ref Rgba32 rPixel = ref image.GetPixelRowSpan(i).GetPinnableReference(); - ref Vector4 r4 = ref vectorArray[i * width]; - - for (int j = 0; j < width; j++) - { - Vector4 v4 = Unsafe.Add(ref rPixel, j).ToVector4(); - v4.X = MathF.Pow(v4.X, Gamma); - v4.Y = MathF.Pow(v4.Y, Gamma); - v4.Z = MathF.Pow(v4.Z, Gamma); - Unsafe.Add(ref r4, j) = v4; - } - }); - - // Create the kernel - Console.WriteLine(">> Creating kernel"); - int diameter = Radius * 2 + 1; - float[] kernel = new float[diameter * diameter]; - int ones = 0; - for (int i = 0; i < diameter; i++) - { - for (int j = 0; j < diameter; j++) - { - if (MathF.Sqrt(MathF.Pow(j - Radius, 2) + MathF.Pow(i - Radius, 2)) - 0.1f <= Radius) - { - kernel[i * diameter + j] = 1; - ones++; - } - } - } - - // Normalize the kernel - Console.WriteLine(">> Normalizing kernel"); - for (int i = 0; i < diameter; i++) - for (int j = 0; j < diameter; j++) - kernel[i * diameter + j] /= ones; - - Console.WriteLine(">> Applying effect"); - using (ReadOnlyBuffer image_gpu = Gpu.Default.AllocateReadOnlyBuffer(vectorArray)) - using (ReadOnlyBuffer kernel_gpu = Gpu.Default.AllocateReadOnlyBuffer(kernel)) - using (ReadWriteBuffer result_gpu = Gpu.Default.AllocateReadWriteBuffer(vectorArray.Length)) - { - // Apply the effect - Gpu.Default.For(height, width, id => - { - Vector4 total = Vector4.Zero; - - for (int y = -Radius; y <= Radius; y++) - { - for (int x = -Radius; x <= Radius; x++) - { - int iy = id.X + y; - int jx = id.Y + x; - - if (iy < 0) iy = -iy; - else if (iy > height) iy = 2 * height - iy; - if (jx < 0) jx = -jx; - else if (jx > width) jx = 2 * width - jx; - - int ki = Radius - y; - int kj = Radius - x; - - total += image_gpu[iy * width + jx] * kernel_gpu[ki * diameter + kj]; - } - } - - result_gpu[id.X * width + id.Y] = total; - }); - - // Copy data back - Console.WriteLine(">> Copying data back"); - result_gpu.GetData(vectorArray); - } - - // Copy the modified image back - Console.WriteLine(">> Storing pixel data"); - Parallel.For(0, height, i => - { - ref Rgba32 rPixel = ref image.GetPixelRowSpan(i).GetPinnableReference(); - ref Vector4 r4 = ref vectorArray[i * width]; - Vector4 low = Vector4.Zero; - Vector4 high = new Vector4(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); - - for (int j = 0; j < width; j++) - { - Vector4 v4 = Unsafe.Add(ref r4, j); - Vector4 clamp = Vector4.Clamp(v4, low, high); - v4.X = MathF.Pow(clamp.X, InverseGamma); - v4.Y = MathF.Pow(clamp.Y, InverseGamma); - v4.Z = MathF.Pow(clamp.Z, InverseGamma); - - Unsafe.Add(ref rPixel, j).FromVector4(v4); - } - }); - - // Save the resulting image Console.WriteLine(">> Saving to disk"); string targetPath = Path.Combine( Path.GetRelativePath(Path.GetDirectoryName(path), @"..\..\..\"), diff --git a/samples/ComputeSharp.BokehBlur/city.jpg b/samples/ComputeSharp.BokehBlur/city.jpg index ba594bed..7a648455 100644 Binary files a/samples/ComputeSharp.BokehBlur/city.jpg and b/samples/ComputeSharp.BokehBlur/city.jpg differ