C# How to: Morphological Edge Detection

Article purpose

The objective of this article is to explore   implemented by means of and  . In addition we explore the concept of implementing morphological .

Sample source code

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

Using the sample application

This article is accompanied by a Sample Application intended to implement all of the concepts illustrated throughout this article. Using the sample application users can easily test and replicate concepts.

Clicking the Load Image button allows users to select source/input from the local system. Filter option categories are: Colour(s), morphology type, edge options and filter size.

This article and sample source code can process colour as source . The user can specify which colour components to include in resulting . The three labelled Red, Green and Blue indicate whether the related colour component features in result .

The four labelled Dilate, Erode, Open and Closed enable the user to select the type of morphological filter to apply.

options include: None, Edge Detection and Image Sharpening. Selecting None results in only the selected morphological filter being applied.

Filter sizes range from 3×3 up to 17×17. The filter size specified determines the intensity of the morphological filter applied.

If desired users are able to save filter result images to the local file system by clicking the Save Image button. The image below is a screenshot of the Morphological Edge Detection sample application in action:

Morphological_Edge_Detection_Sample_Application

Morphology – Image Erosion and Dilation

and are implementations of , a subset of . In simpler terms can be defined by this :

Dilation is one of the two basic operators in the area of , the other being . It is typically applied to , but there are versions that work on . The basic effect of the operator on a binary image is to gradually enlarge the boundaries of regions of foreground (i.e. white pixels, typically). Thus areas of foreground pixels grow in size while holes within those regions become smaller.

being a related concept is defined by this :

Erosion is one of the two basic operators in the area of , the other being . It is typically applied to , but there are versions that work on . The basic effect of the operator on a binary image is to erode away the boundaries of regions of foreground (i.e. white pixels, typically). Thus areas of foreground pixels shrink in size, and holes within those areas become larger.

From the definitions listed above we gather that increases the size of edges contained in an . In contrast decreases or shrinks the size of an ’s edges.

Image Edge Detection

We gain a good definition of from ’s article on :

Edge detection is the name for a set of mathematical methods which aim at identifying points in a at which the changes sharply or, more formally, has discontinuities. The points at which image brightness changes sharply are typically organized into a set of curved line segments termed edges. The same problem of finding discontinuities in 1D signals is known as and the problem of finding signal discontinuities over time is known as . Edge detection is a fundamental tool in , and , particularly in the areas of and .

In this article we implement based on the type of being performed. In the case of the eroded is subtracted from the original resulting in an with pronounced edges. When implementing , is achieved by subtracting the original from the dilated .

Image Sharpening

is often referred to by the term , from Wikipedia we gain the following :

Edge enhancement is an filter that enhances the edge contrast of an or in an attempt to improve its acutance (apparent sharpness).

The filter works by identifying sharp edge boundaries in the image, such as the edge between a subject and a background of a contrasting color, and increasing the image contrast in the area immediately around the edge. This has the effect of creating subtle bright and dark highlights on either side of any edges in the image, called and undershoot, leading the edge to look more defined when viewed from a typical viewing distance.

In this article we implement by first creating an which we then add to the original , resulting in an with enhanced edges.

Implementing Morphological Filters

The sample source code provides the definition of the DilateAndErodeFilter targeting the class. The DilateAndErodeFilter as a single method implementation is capable of applying a specified morphological filter, and . The following code snippet details the implementation of the the DilateAndErodeFilter :

public static Bitmap DilateAndErodeFilter(this Bitmap sourceBitmap,  
                                        int matrixSize, 
                                        MorphologyType morphType, 
                                        bool applyBlue = true, 
                                        bool applyGreen = true, 
                                        bool applyRed = true,
                                        MorphologyEdgeType edgeType = 
                                        MorphologyEdgeType.None)  
{ 
    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);
int filterOffset = (matrixSize - 1) / 2; int calcOffset = 0;
int byteOffset = 0;
int blue = 0; int green = 0; int red = 0;
byte morphResetValue = 0;
if (morphType == MorphologyType.Erosion) { morphResetValue = 255; }
for (int offsetY = filterOffset; offsetY < sourceBitmap.Height - filterOffset; offsetY++) { for (int offsetX = filterOffset; offsetX < sourceBitmap.Width - filterOffset; offsetX++) { byteOffset = offsetY * sourceData.Stride + offsetX * 4;
blue = morphResetValue; green = morphResetValue; red = morphResetValue;
if (morphType == MorphologyType.Dilation) { for (int filterY = -filterOffset; filterY <= filterOffset; filterY++) { for (int filterX = -filterOffset; filterX <= filterOffset; filterX++) { calcOffset = byteOffset + (filterX * 4) + (filterY * sourceData.Stride);
if (pixelBuffer[calcOffset] > blue) { blue = pixelBuffer[calcOffset]; }
if (pixelBuffer[calcOffset + 1] > green) { green = pixelBuffer[calcOffset + 1]; }
if (pixelBuffer[calcOffset + 2] > red) { red = pixelBuffer[calcOffset + 2]; } } } } else if (morphType == MorphologyType.Erosion) { for (int filterY = -filterOffset; filterY <= filterOffset; filterY++) { for (int filterX = -filterOffset; filterX <= filterOffset; filterX++) { calcOffset = byteOffset + (filterX * 4) + (filterY * sourceData.Stride);
if (pixelBuffer[calcOffset] < blue) { blue = pixelBuffer[calcOffset]; }
if (pixelBuffer[calcOffset + 1] < green) { green = pixelBuffer[calcOffset + 1]; }
if (pixelBuffer[calcOffset + 2] < red) { red = pixelBuffer[calcOffset + 2]; } } } }
if (applyBlue == false ) { blue = pixelBuffer[byteOffset]; }
if (applyGreen == false ) { green = pixelBuffer[byteOffset + 1]; }
if (applyRed == false ) { red = pixelBuffer[byteOffset + 2]; }
if (edgeType == MorphologyEdgeType.EdgeDetection || edgeType == MorphologyEdgeType.SharpenEdgeDetection) { if (morphType == MorphologyType.Dilation) { blue = blue - pixelBuffer[byteOffset]; green = green - pixelBuffer[byteOffset + 1]; red = red - pixelBuffer[byteOffset + 2]; } else if (morphType == MorphologyType.Erosion) { blue = pixelBuffer[byteOffset] - blue; green = pixelBuffer[byteOffset + 1] - green; red = pixelBuffer[byteOffset + 2] - red; }
if (edgeType == MorphologyEdgeType.SharpenEdgeDetection) { blue += pixelBuffer[byteOffset]; green += pixelBuffer[byteOffset + 1]; red += pixelBuffer[byteOffset + 2]; } }
blue = (blue > 255 ? 255 : (blue < 0 ? 0 : blue)); green = (green > 255 ? 255 : (green < 0 ? 0 : green)); red = (red > 255 ? 255 : (red < 0 ? 0 : red));
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; }

Sample Images

The source/input used in this article is licensed under the Creative Commons Attribution-Share Alike 3.0 Unported license and can be downloaded from Wikipedia: http://en.wikipedia.org/wiki/File:Bathroom_with_bathtube.jpg

Original Image

1280px-Bathroom_with_bathtube

Erosion 3×3, Edge Detect, Red, Green and Blue

Erosion 3x3 Edge Detect Red, Green and Blue

Erosion 3×3, Edge Detect, Blue

Erosion 3x3, Edge Detect, Blue

Erosion 3×3, Edge Detect, Green and Blue

Erosion 3x3, Edge Detect, Green and Blue

Erosion 3×3, Edge Detect, Red

Erosion 3x3, Edge Detect, Red

Erosion 3×3, Edge Detect, Red and Blue

Erosion 3x3, Edge Detect, Red and Blue

Erosion 3×3, Edge Detect, Red and Green

Erosion 3x3, Edge Detect, Red and Green

Erosion 7×7, Sharpen, Red, Green and Blue

Erosion 7x7, Sharpen, Red, Green and Blue

Erosion 7×7, Sharpen, Blue

Erosion 7x7, Sharpen, Blue

Erosion 7×7, Sharpen, Green

Erosion 7x7, Sharpen, Green

Erosion 7×7, Sharpen, Green and Blue

Erosion 7x7, Sharpen, Green and Blue

Erosion 7×7, Sharpen, Red

Erosion 7x7, Sharpen, Red

Erosion 7×7, Sharpen, Red and Blue

Erosion 7x7, Sharpen, Red and Blue

Erosion 7×7, Sharpen, Red and Green

Erosion 7x7, Sharpen, Red and Green

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:

31 Responses to “C# How to: Morphological Edge Detection”



  1. 1 C# How to: Boolean Edge Detection | Software by Default Trackback on June 1, 2013 at 2:09 AM
  2. 2 C# How to: Gradient Based Edge Detection | Software by Default Trackback on June 1, 2013 at 4:47 PM
  3. 3 C# How to: Image Cartoon Effect | Software by Default Trackback on June 2, 2013 at 4:13 PM
  4. 4 C# How to: Sharpen Edge Detection | Software by Default Trackback on June 7, 2013 at 5:12 AM
  5. 5 C# How to: Calculating Gaussian Kernels | Software by Default Trackback on June 8, 2013 at 10:59 AM
  6. 6 C# How to: Image Blur | Software by Default Trackback on June 9, 2013 at 10:20 PM
  7. 7 C# How to: Image Transform Rotate | Software by Default Trackback on June 16, 2013 at 10:40 AM
  8. 8 C# How to: Image Transform Shear | Software by Default Trackback on June 16, 2013 at 5:45 PM
  9. 9 C# How to: Compass Edge Detection | Software by Default Trackback on June 22, 2013 at 9:35 PM
  10. 10 C# How to: Oil Painting and Cartoon Filter | Software by Default Trackback on June 30, 2013 at 10:47 AM
  11. 11 C# How to: Stained Glass Image Filter | Software by Default Trackback on June 30, 2013 at 10:50 AM
  12. 12 C# How to: Image Erosion and Dilation | Software by Default Trackback on June 30, 2013 at 2:10 PM
  13. 13 C# How to: Image Colour Average | Software by Default Trackback on June 30, 2013 at 2:20 PM
  14. 14 C# How to: Image Unsharp Mask | Software by Default Trackback on June 30, 2013 at 2:28 PM
  15. 15 C# How to: Image Median Filter | Software by Default Trackback on June 30, 2013 at 3:16 PM
  16. 16 C# How to: Difference Of Gaussians | Software by Default Trackback on June 30, 2013 at 3:27 PM
  17. 17 C# How to: Image Edge Detection | Software by Default Trackback on June 30, 2013 at 3:33 PM
  18. 18 C# How to: Image Convolution | Software by Default Trackback on June 30, 2013 at 3:55 PM
  19. 19 C# How to: Generate a Web Service from WSDL | Software by Default Trackback on June 30, 2013 at 4:08 PM
  20. 20 C# How to: Decoding/Converting Base64 strings to Bitmap images | Software by Default Trackback on June 30, 2013 at 4:14 PM
  21. 21 C# How to: Bitmap Colour Substitution implementing thresholds | Software by Default Trackback on July 6, 2013 at 4:33 PM
  22. 22 C# How to: Swapping Bitmap ARGB Colour Channels | Software by Default Trackback on July 6, 2013 at 5:02 PM
  23. 23 C# How to: Image filtering by directly manipulating Pixel ARGB values | Software by Default Trackback on July 8, 2013 at 2:57 AM
  24. 24 C# How to: Image ASCII Art | Software by Default Trackback on July 14, 2013 at 7:22 AM
  25. 25 C# How to: Weighted Difference of Gaussians | Software by Default Trackback on July 14, 2013 at 8:11 PM
  26. 26 C# How to: Image Boundary Extraction | Software by Default Trackback on July 21, 2013 at 10:24 AM
  27. 27 C# How to: Image Abstract Colours Filter | Software by Default Trackback on July 28, 2013 at 7:41 PM
  28. 28 C# How to: Fuzzy Blur Filter | Software by Default Trackback on August 9, 2013 at 6:39 AM
  29. 29 C# How to: Image Distortion Blur | Software by Default Trackback on August 9, 2013 at 10:13 PM
  30. 30 C# How to: Standard Deviation Edge Detection | Software by Default Trackback on August 8, 2015 at 8:10 AM
  31. 31 C# How to: Min/Max Edge Detection | Software by Default Trackback on August 9, 2015 at 11:30 AM

Leave a comment




Dewald Esterhuizen

Blog Stats

  • 869,623 hits

Enter your email address to follow and receive notifications of new posts by email.

Join 228 other subscribers

Archives

RSS SoftwareByDefault on MSDN

  • An error has occurred; the feed is probably down. Try again later.