Write a Metal compute kernel to Gaussian blur an image.
- User
Write a Metal compute kernel to Gaussian blur an image.
- Assistant
Here is a Metal compute kernel to Gaussian blur an image:
#include <metal_stdlib> #include <simd/simd.h> using namespace metal; kernel void gaussianBlur(texture2d<float, access::read> inTexture [[texture(0)]], texture2d<float, access::write> outTexture [[texture(1)]], uint2 gid [[thread_position_in_grid]]) { // Image size uint width = inTexture.get_width(); uint height = inTexture.get_height(); // Gaussian kernel size (must be odd) int kernelSize = 5; // Sigma value for Gaussian distribution float sigma = 2.0; // Calculate Gaussian kernel weights float weights[kernelSize]; float sum = 0.0; for (int i = 0; i < kernelSize; i++) { float x = (float(i) - kernelSize / 2.0); weights[i] = exp(-x * x / (2.0 * sigma * sigma)) / (sigma * sqrt(2.0 * M_PI)); sum += weights[i]; } // Normalize weights to sum to 1.0 for (int i = 0; i < kernelSize; i++) { weights[i] /= sum; } // Apply Gaussian blur float4 color = float4(0.0); for (int x = -kernelSize / 2; x <= kernelSize / 2; x++) { for (int y = -kernelSize / 2; y <= kernelSize / 2; y++) { int2 samplePos = gid + int2(x, y); if (all(samplePos >= 0 && samplePos < int2(width, height))) { float4 sampleColor = inTexture.read(samplePos); color += sampleColor * weights[x + kernelSize / 2] * weights[y + kernelSize / 2]; } } } // Write blurred color to output outTexture.write(color, gid); }This kernel:
- Defines a 5x5 Gaussian kernel with sigma = 2.0
- Calculates the weights for the kernel
- Loops over the kernel size and samples the input texture
- Multiplies each sample by the kernel weight and accumulates
- Writes the blurred color to the output texture
This will perform a Gaussian blur on the input texture and write the result to the output texture.
- User
Explain how your code avoids memory errors from going outside the bounds of the image
- Assistant
The code contains checks to ensure it does not sample outside the bounds of the input image. Specifically, it has these checks:
int2 samplePos = gid + int2(x, y); if (all(samplePos >= 0 && samplePos < int2(width, height))) { // Sample the texture at samplePos }This checks that the sample position
samplePosis within the bounds of the image (width, height) before sampling the texture at that position. If the sample is outside the image, it is skipped.Without these checks, the kernel would attempt to sample at invalid texture coordinates outside the image bounds, resulting in undefined behavior and potentially memory errors.
By verifying each sample position is within the valid image region before sampling, we avoid going out of bounds and ensure only valid samples are used in the blur calculation.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.