博主做的很简单,大家看一看就好了......
用到的算法是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; } pin_1 += oldData.Stride - oldData.Width * 3; pin_2 += oldData.Stride - oldData.Width * 3; pout += newData.Stride - newData.Width * 3; } //这里博主加粗了一下线条- -,不喜欢的同学可以删了这段代码 byte* pin_5 = (byte*)(newData.Scan0.ToPointer()); for (int y = 0; y < oldData.Height - 1; y++) { for (int x = 3; x < oldData.Width; x++) { if(pin_5[0]==0&&pin_5[1]==0&&pin_5[2]==0) { pin_5[-3] = 0; pin_5[-2] = 0; pin_5[-1] = 0; //边缘点的前一个像素点置为黑色(注意一定要是遍历过的像素点) } pin_5 += 3; } pin_5 += newData.Stride - newData.Width * 3; } //这段代码是把原图和边缘图重合 byte* pin_3= (byte*)(oldData.Scan0.ToPointer()); byte* pin_4 = (byte*)(newData.Scan0.ToPointer()); for (int y = 0; y < oldData.Height - 1; y++) { for (int x = 0; x < oldData.Width; x++) { if (pin_4[0] == 255 && pin_4[1]==255 && pin_4[2]==255) { pin_4[0] = pin_3[0]; pin_4[1] = pin_3[1]; pin_4[2] = pin_3[2]; } pin_3 += 3; pin_4 += 3; } pin_3 += oldData.Stride - oldData.Width * 3; pin_4 += newData.Stride - newData.Width * 3; } //...... bitmap.UnlockBits(newData); MyBitmap.UnlockBits(oldData); this.pBox.Image = bitmap; } } }
例子1:
例子2: