集合A(输入图像)被集合B(结构元素)腐蚀,表示为 AΘB, 其定义为 AΘB={x:B+x⊂A}
可见,AΘB由将B平移x仍包含在A内的所有点x组成。如果将B视为模板,那么AΘB则由在将模板平移的过程中,所有可填入A内部的模板的原点组成。
示例:数学形态学腐蚀图像
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
namespace ImageCorrosion
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Image image2 = Corrosion(pictureBox1.Image);
pictureBox2.Image = image2;
}
//数学形态学—腐蚀图片
private Image Corrosion(Image image)
{
//定义一个3x3的结构模板,原点[0,0]。
int[,] templet = new int[,] {
{ 1, 1, 1 },
{ 1, 1, 1 },
{ 1, 1, 1 }
};
Bitmap bmp = new Bitmap(image);
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
Bitmap bmp_clone = bmp.Clone(rect, PixelFormat.Format24bppRgb);
for (int y=0; y<bmp.Height; y++)
{
for (int x=0; x< bmp.Width; x++)
{
Color c = bmp.GetPixel(x, y);
if (IsMatchTemplet(x, y, bmp, templet))
{
//保留此像素
bmp_clone.SetPixel(x,y,c);
}
else
{
//删除此像素(用背景色(黑色)进行腐蚀)
bmp_clone.SetPixel(x, y, Color.Black);
}
}
}
return bmp_clone;
}
//判断模板所覆盖的图像区域与模板是否匹配
//模板中1对应目标图像,0对应背景
private bool IsMatchTemplet(int x, int y, Bitmap bmp, int[,] templet)
{
bool match = true;
int rowLength = templet.GetLength(0);
int colLength = templet.GetLength(1);
for (int i=0; i<rowLength; i++)
{
if (y+i >= bmp.Height)
{
match = false;
goto EXIT;
}
for (int j=0; j<colLength; j++)
{
if (x+j >= bmp.Width)
{
match = false;
goto EXIT;
}
Color c = bmp.GetPixel(x+j, y+i);
//需要根据实际情况做判断,本示例仅判断R通道
int v = templet[i, j];
match = (c.R == 255 && v == 1) || (c.R == 0 && v == 0);
if (!match)
goto EXIT;
}
}
EXIT:
return match;
}
}
}