用到的算法是robert算子,这是一种比较简单的算法:
f(x,y)=sqrt((g(x,y)-g(x+1,y+1))^2+(g(x+1,y)-g(x,y+1))^2)
博主一共写了三段代码,第一段是边缘提取,第二段是线条加粗,第三段是原图和边缘图重合,三段代码可以放在一起,但为了看得清晰我就把他们分开了。
简单粗暴直接上代码!
private void Image_Test()
{
if (this.pBox.Image != null)
{
int Height = this.pBox.Image.Height;
int Width = this.pBox.Image.Width;
Bitmap bitmap = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
Bitmap MyBitmap = (Bitmap)this.pBox.Image;
BitmapData oldData = MyBitmap.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); //原图
BitmapData newData = bitmap.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); //新图即边缘图
unsafe
{
//首先第一段代码是提取边缘,边缘置为黑色,其他部分置为白色
byte* pin_1 = (byte*)(oldData.Scan0.ToPointer());
byte* pin_2 = pin_1 + (oldData.Stride);
byte* pout = (byte*)(newData.Scan0.ToPointer());
for (int y = 0; y < oldData.Height - 1; y++)
{
for (int x = 0; x < oldData.Width; x++)
{
//使用robert算子
double b = System.Math.Sqrt(((double)pin_1[0] - (double)(pin_2[0] + 3)) * ((double)pin_1[0] - (double)(pin_2[0] + 3)) + ((double)(pin_1[0] + 3) - (double)pin_2[0]) * ((double)(pin_1[0] + 3) - (double)pin_2[0]));
double g = System.Math.Sqrt(((double)pin_1[1] - (double)(pin_2[1] + 3)) * ((double)pin_1[1] - (double)(pin_2[1] + 3)) + ((double)(pin_1[1] + 3) - (double)pin_2[1]) * ((double)(pin_1[1] + 3) - (double)pin_2[1]));
double r = System.Math.Sqrt(((double)pin_1[2] - (double)(pin_2[2] + 3)) * ((double)pin_1[2] - (double)(pin_2[2] + 3)) + ((double)(pin_1[2] + 3) - (double)pin_2[2]) * ((double)(pin_1[2] + 3) - (double)pin_2[2]));
double bgr = b + g + r;//博主一直在纠结要不要除以3,感觉没差,选阈值的时候调整一下就好了- -
if (bgr > 80) //阈值,超过阈值判定为边缘(选取适当的阈值)
{
b = 0;
g = 0;
r = 0;
}
else
{
b = 255;
g = 255;
r = 255;
}
pout[0] = (byte)(b);
pout[1] = (byte)(g);
pout[2] = (byte)(r);
pin_1 = pin_1 + 3;
pin_2 = pin_2 + 3;
pout = pout + 3;