C#图像处理之边缘检测(Sobel)的方法
程序员文章站
2022-05-26 15:20:14
本文实例讲述了c#图像处理之边缘检测(sobel)的方法。分享给大家供大家参考。具体如下:
//定义sobel算子函数
private static bitma...
本文实例讲述了c#图像处理之边缘检测(sobel)的方法。分享给大家供大家参考。具体如下:
//定义sobel算子函数 private static bitmap sobel(bitmap a) { int w = a.width; int h = a.height; try { bitmap dstbitmap = new bitmap(w, h, system.drawing.imaging.pixelformat.format24bpprgb); system.drawing.imaging.bitmapdata srcdata = a.lockbits(new rectangle (0, 0, w, h), system.drawing.imaging.imagelockmode.readonly, system.drawing.imaging.pixelformat.format24bpprgb); system.drawing.imaging.bitmapdata dstdata = dstbitmap.lockbits(new rectangle (0, 0, w, h), system.drawing.imaging.imagelockmode.writeonly, system.drawing.imaging.pixelformat.format24bpprgb); unsafe { byte* pin = (byte*)srcdata.scan0.topointer(); byte* pout = (byte*)dstdata.scan0.topointer(); byte* p; int stride = srcdata.stride; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { //边缘八个点像素不变 if (x == 0 || x == w - 1 || y == 0 || y == h - 1) { pout[0] = pin[0]; pout[1] = pin[1]; pout[2] = pin[2]; } else { int r0, r1, r2, r3, r4, r5, r6, r7, r8; int g1, g2, g3, g4, g5, g6, g7, g8, g0; int b1, b2, b3, b4, b5, b6, b7, b8, b0; double vr, vg, vb; //左上 p = pin - stride - 3; r1 = p[2]; g1 = p[1]; b1 = p[0]; //正上 p = pin - stride; r2 = p[2]; g2 = p[1]; b2 = p[0]; //右上 p = pin - stride + 3; r3 = p[2]; g3 = p[1]; b3 = p[0]; //左 p = pin - 3; r4 = p[2]; g4 = p[1]; b4 = p[0]; //右 p = pin + 3; r5 = p[2]; g5 = p[1]; b5 = p[0]; //左下 p = pin + stride - 3; r6 = p[2]; g6 = p[1]; b6 = p[0]; //正下 p = pin + stride; r7 = p[2]; g7 = p[1]; b7 = p[0]; // 右下 p = pin + stride + 3; r8 = p[2]; g8 = p[1]; b8 = p[0]; //中心点 p = pin; r0 = p[2]; g0 = p[1]; b0 = p[0]; //使用模板 vr = (double)(math .abs (r1+2*r4+r6-r3-2*r5-r8)+math .abs (r1+2*r2+r3-r6-2*r7-r8)); vg = (double)(math .abs (g1+2*g4+g6-g3-2*g5-g8)+math .abs (g1+2*g2+g3-g6-2*g7-g8)); vb = (double)(math .abs (b1+2*b4+b6-b3-2*b5-b8)+math .abs (b1+2*b2+b3-b6-2*b7-b8)); if (vr > 0) { vr = math.min(255, vr); } else { vr = math.max(0, vr); } if (vg > 0) { vg = math.min(255, vg); } else { vg = math.max(0, vg); } if (vb > 0) { vb = math.min(255, vb); } else { vb = math.max(0, vb); } pout[0] = (byte)vb; pout[1] = (byte)vg; pout[2] = (byte)vr; } pin += 3; pout += 3; } pin += srcdata.stride - w * 3; pout += srcdata.stride - w * 3; } } a.unlockbits(srcdata); dstbitmap.unlockbits(dstdata); return dstbitmap; } catch { return null; } }
希望本文所述对大家的c#程序设计有所帮助。