### Article purpose

In this article we explore the concept of Difference of Gaussians edge detection. This article implements image convolution as a means of achieving Gaussian blurring. All of the concepts explored are implemented by accessing and manipulating the raw pixel data exposed by an image, no GDI+ or conventional drawing code is required.

### Sample source code

This article is accompanied by a sample source code Visual Studio project which is available for download here.

### Using the Sample Application

The concepts explored in this article can be easily replicated by making use of the ** Sample Application**, which forms part of the associated sample source code accompanying this article.

When using the ** Difference Of Gaussians** sample application you can specify a input/source image by clicking the

**button. The dropdown combobox towards the bottom middle part of the screen relates the various edge detection methods discussed.**

*Load Image*If desired a user can save the resulting edge detection image to the local file system by clicking the ** Save Image** button.

The following image is screenshot of the ** Difference Of Gaussians** sample application in action:

### What is Difference of Gaussians?

Difference of Gaussians, commonly abbreviated as DoG, is a method of implementing image edge detection. Central to the Difference of Gaussians method of edge detection is the application of Gaussian image blur.

From Wikipedia we gain the following explanation:

In imaging science,

Difference of Gaussiansis a feature enhancement algorithm that involves the subtraction of one blurred version of an original image from another, less blurred version of the original. In the simple case of grayscale images, the blurred images are obtained by convolving the original grayscale images with Gaussian kernels having differing standard deviations. Blurring an image using a Gaussian kernel suppresses only high-frequency spatial information. Subtracting one image from the other preserves spatial information that lies between the range of frequencies that are preserved in the two blurred images. Thus, the difference of Gaussians is a band-pass filter that discards all but a handful of spatial frequencies that are present in the original grayscale image.

In simple terms Difference of Gaussians can be implemented by applying two Gaussian blurs of different intensity levels to the same source image. The resulting image is then created by subtracting the two images of different Gaussian blurring.

### Applying a Convolution Matrix filter

In the sample source code accompanying this article Gaussian image blurring is applied by invoking the ** ConvolutionFilter** method. This method accepts a two dimensional array of type

**representing the convolution matrix/kernel. This method is also capable of first converting source images to grayscale, which can be specified as a method parameter. Resulting images sometimes tend to be very dark, which can be corrected by specifying a suitable bias value.**

*double*The following code snippet provides the implementation of the ** ConvolutionFilter** method:

private static Bitmap ConvolutionFilter(Bitmap sourceBitmap, double[,] filterMatrix, double factor = 1, int bias = 0, bool grayscale = false ) { BitmapData sourceData = sourceBitmap.LockBits(new Rectangle (0, 0, sourceBitmap.Width, sourceBitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

byte[] pixelBuffer = new byte[sourceData.Stride * sourceData.Height]; byte[] resultBuffer = new byte[sourceData.Stride * sourceData.Height];

Marshal.Copy(sourceData.Scan0, pixelBuffer, 0, pixelBuffer.Length); sourceBitmap.UnlockBits(sourceData);

if (grayscale == true) { float rgb = 0;

for (int k = 0; k < pixelBuffer.Length; k += 4) { rgb = pixelBuffer[k] * 0.11f; rgb += pixelBuffer[k + 1] * 0.59f; rgb += pixelBuffer[k + 2] * 0.3f;

pixelBuffer[k] = (byte )rgb; pixelBuffer[k + 1] = pixelBuffer[k]; pixelBuffer[k + 2] = pixelBuffer[k]; pixelBuffer[k + 3] = 255; } }

double blue = 0.0; double green = 0.0; double red = 0.0;

int filterWidth = filterMatrix.GetLength(1); int filterHeight = filterMatrix.GetLength(0);

int filterOffset = (filterWidth-1) / 2; int calcOffset = 0;

int byteOffset = 0;

for (int offsetY = filterOffset; offsetY < sourceBitmap.Height - filterOffset; offsetY++) { for (int offsetX = filterOffset; offsetX < sourceBitmap.Width - filterOffset; offsetX++) { blue = 0; green = 0; red = 0;

byteOffset = offsetY * sourceData.Stride + offsetX * 4;

for (int filterY = -filterOffset; filterY <= filterOffset; filterY++) { for (int filterX = -filterOffset; filterX <= filterOffset; filterX++) {

calcOffset = byteOffset + (filterX * 4) + (filterY * sourceData.Stride);

blue += (double)(pixelBuffer[calcOffset]) * filterMatrix[filterY + filterOffset, filterX + filterOffset];

green += (double)(pixelBuffer[calcOffset + 1]) * filterMatrix[filterY + filterOffset, filterX + filterOffset];

red += (double)(pixelBuffer[calcOffset + 2]) * filterMatrix[filterY + filterOffset, filterX + filterOffset]; } }

blue = factor * blue + bias; green = factor * green + bias; red = factor * red + bias;

if (blue > 255) { blue = 255; } else if (blue < 0) { blue = 0; }

if (green > 255) { green = 255; } else if (green < 0) { green = 0; }

if (red > 255) { red = 255; } else if (red < 0) { red = 0; }

resultBuffer[byteOffset] = (byte )(blue); resultBuffer[byteOffset + 1] = (byte )(green); resultBuffer[byteOffset + 2] = (byte )(red); resultBuffer[byteOffset + 3] = 255; } }

Bitmap resultBitmap = new Bitmap(sourceBitmap.Width, sourceBitmap.Height); BitmapData resultData = resultBitmap.LockBits(new Rectangle (0, 0, resultBitmap.Width, resultBitmap.Height), ImageLockMode .WriteOnly, PixelFormat.Format32bppArgb);

Marshal.Copy(resultBuffer, 0, resultData.Scan0, resultBuffer.Length); resultBitmap.UnlockBits(resultData);

return resultBitmap; }

### The Gaussian Matrix

The sample source code defines three Gaussian matrix/kernel values, a ** 3×3** matrix and two slightly different

**matrices. The**

*5×5***matrix requires a factor of**

*Gaussian3x3***, the**

*1 / 16***matrix a factor of**

*Gaussian5x5Type1***and the factor required by the**

*1 / 159***equates to**

*Gaussian5x5Type2***.**

*1 / 256*public static class Matrix { public static double[,] Gaussian3x3 { get { return new double[,] { { 1, 2, 1, }, { 2, 4, 2, }, { 1, 2, 1, }, }; } }

public static double[,] Gaussian5x5Type1 { get { return new double[,] { { 2, 04, 05, 04, 2 }, { 4, 09, 12, 09, 4 }, { 5, 12, 15, 12, 5 }, { 4, 09, 12, 09, 4 }, { 2, 04, 05, 04, 2 }, }; } }

public static double[,] Gaussian5x5Type2 { get { return new double[,] { { 1, 4, 6, 4, 1 }, { 4, 16, 24, 16, 4 }, { 6, 24, 36, 24, 6 }, { 4, 16, 24, 16, 4 }, { 1, 4, 6, 4, 1 }, }; } } }

### Subtracting Images

When implementing the Difference of Gaussians method of edge detection after having applied two varying levels of Gaussian blurring the resulting images need to be subtracted. The sample source code associated with this article implements the ** SubtractImage** extension method when subtracting images.

The following code snippet details the implementation of the ** SubtractImage** extension method:

private static void SubtractImage(this Bitmap subtractFrom, Bitmap subtractValue, bool invert = false, int bias = 0) { BitmapData sourceData = subtractFrom.LockBits(new Rectangle(0, 0, subtractFrom.Width, subtractFrom.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

byte[] resultBuffer = new byte[sourceData.Stride * sourceData.Height];

Marshal.Copy(sourceData.Scan0, resultBuffer, 0, resultBuffer.Length);

BitmapData subtractData = subtractValue.LockBits(new Rectangle(0, 0, subtractValue.Width, subtractValue.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

byte[] subtractBuffer = new byte[subtractData.Stride * subtractData.Height];

Marshal.Copy(subtractData.Scan0, subtractBuffer, 0, subtractBuffer.Length);

subtractValue.UnlockBits(subtractData);

int blue = 0; int green = 0; int red = 0;

for (int k = 0; k < resultBuffer.Length && k < subtractBuffer.Length; k += 4) { if (invert == true ) { blue = 255 - resultBuffer[k] - subtractBuffer[k] + bias;

green = 255 - resultBuffer[k + 1] - subtractBuffer[k + 1] + bias;

red = 255 - resultBuffer[k + 2] - subtractBuffer[k + 2] + bias; } else { blue = resultBuffer[k] - subtractBuffer[k] + bias;

green = resultBuffer[k + 1] - subtractBuffer[k + 1] + bias;

red = resultBuffer[k + 2] - subtractBuffer[k + 2] + bias; }

blue = (blue < 0 ? 0 : (blue > 255 ? 255 : blue)); green = (green < 0 ? 0 : (green > 255 ? 255 : green)); red = (red < 0 ? 0 : (red > 255 ? 255 : red));

resultBuffer[k] = (byte )blue; resultBuffer[k + 1] = (byte )green; resultBuffer[k + 2] = (byte )red; resultBuffer[k + 3] = 255; }

Marshal.Copy(resultBuffer, 0, sourceData.Scan0, resultBuffer.Length);

subtractFrom.UnlockBits(sourceData); }

### Difference of Gaussians Extension methods

The sample source code implements Difference of Gaussians edge detection by means of two extension methods: ** DifferenceOfGaussians3x5Type1** and

**. Both methods are virtually identical, the only difference being the**

*DifferenceOfGaussians3x5Type2***Gaussian matrix being implemented.**

*5×5*Both methods create two new images, each having a Gaussian blur of different levels of intensity applied. The two new images are subtracted in order to create a single resulting image.

The following source code snippet provides the implementation of the ** DifferenceOfGaussians3x5Type1** and

**extension methods:**

*DifferenceOfGaussians3x5Type2*public static Bitmap DifferenceOfGaussians3x5Type1( this Bitmap sourceBitmap, bool grayscale = false, bool invert = false, int bias = 0) { Bitmap bitmap3x3 = ExtBitmap.ConvolutionFilter(sourceBitmap, Matrix.Gaussian3x3, 1.0 / 16.0, 0, grayscale);

Bitmap bitmap5x5 = ExtBitmap.ConvolutionFilter(sourceBitmap, Matrix.Gaussian5x5Type1, 1.0 / 159.0, 0, grayscale);

bitmap3x3.SubtractImage(bitmap5x5, invert, bias);

return bitmap3x3; }

public static Bitmap DifferenceOfGaussians3x5Type2( this Bitmap sourceBitmap, bool grayscale = false, bool invert = false, int bias = 0) { Bitmap bitmap3x3 = ExtBitmap.ConvolutionFilter(sourceBitmap, Matrix.Gaussian3x3, 1.0 / 16.0, 0, true );

Bitmap bitmap5x5 = ExtBitmap.ConvolutionFilter(sourceBitmap, Matrix.Gaussian5x5Type2, 1.0 / 256.0, 0, true );

bitmap3x3.SubtractImage(bitmap5x5, invert, bias);

return bitmap3x3; }

### Sample Images

The original sample image used in this article is licensed under the Creative Commons Attribution-Share Alike 2.0 Generic license. The original author is attributed as Andrew Dunn – http://www.andrewdunnphoto.com/

*The Original Image*

*Difference Of Gaussians 3×5 Type1*

*Difference Of Gaussians 3×5 Type2*

*Difference Of Gaussians 3×5 Type1 Bias 128*

*Difference Of Gaussians 3×5 Type 2 Bias 96*

### Related Articles and Feedback

Feedback and questions are always encouraged. If you know of an alternative implementation or have ideas on a more efficient implementation please share in the comments section.

I’ve published a number of articles related to imaging and images of which you can find URL links here:

- C# How to: Image filtering by directly manipulating Pixel ARGB values
- C# How to: Image filtering implemented using a ColorMatrix
- C# How to: Blending Bitmap images using colour filters
- C# How to: Bitmap Colour Substitution implementing thresholds
- C# How to: Generating Icons from Images
- C# How to: Swapping Bitmap ARGB Colour Channels
- C# How to: Bitmap Pixel manipulation using LINQ Queries
- C# How to: Linq to Bitmaps – Partial Colour Inversion
- C# How to: Bitmap Colour Balance
- C# How to: Bi-tonal Bitmaps
- C# How to: Bitmap Colour Tint
- C# How to: Bitmap Colour Shading
- C# How to: Image Solarise
- C# How to: Image Contrast
- C# How to: Bitwise Bitmap Blending
- C# How to: Image Arithmetic
- C# How to: Image Convolution
- C# How to: Image Edge Detection
- C# How to: Image Median Filter
- C# How to: Image Unsharp Mask
- C# How to: Image Colour Average
- C# How to: Image Erosion and Dilation
- C# How to: Morphological Edge Detection
- C# How to: Boolean Edge Detection
- C# How to: Gradient Based Edge Detection
- C# How to: Sharpen Edge Detection
- C# How to: Image Cartoon Effect
- C# How to: Calculating Gaussian Kernels
- C# How to: Image Blur
- C# How to: Image Transform Rotate
- C# How to: Image Transform Shear
- C# How to: Compass Edge Detection
- C# How to: Oil Painting and Cartoon Filter
- C# How to: Stained Glass Image Filter

## 29 Responses to “C# How to: Difference Of Gaussians”