在图像处理中需要有边缘鲜明的图像,即需对图像进行锐化。因为锐化能够突出图像的边缘信息。加强图像的轮廓特征,使之便于人眼的观察或机器的识别。另外,从处理效果来看,锐化是一种与滤波相反的图像处理技术。
常用的锐化算法有梯度孙子,一阶的sobel算子和Prewitt算子以及二阶的拉普拉斯运算等。实际上,根据锐化的目的,可以采用多种方法来达到其效果。在此采用一种简单的锐化方法,即原像素+边缘像素平均值*系数。
g(x,y)=f(i,j)+k/N(f(x,y)-f(i,j))对图像上的每一点都是这样的。g(x,y)为锐化后的像素颜色值;N为邻域像素点;k为锐化系数。i,j属于当前像素点(x,y)的邻域。一般就是8个点啦。
代码如下:
//锐化 public static Bitmap sharpen(Bitmap b) { if (b == null) { MessageBox.Show("无图像可处理", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); return null; } string sp = Interaction.InputBox("请输入一个0~1之间的锐化参数", "锐化参数设置", "0.5", 100, 100); if (sp == "" || Convert.ToSingle(sp) < 0 || Convert.ToSingle(sp) > 1) { MessageBox.Show("锐化参数必须在0~1之间", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } float val = Convert.ToSingle(sp); int w = b.Width; int h = b.Height; try { Bitmap bmprtn = new Bitmap(w, h, PixelFormat.Format24bppRgb); BitmapData srcData = b.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); BitmapData dstData = bmprtn.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb); unsafe { byte* pIn = (byte*)srcData.Scan0.ToPointer(); byte* pOut = (byte*)dstData.Scan0.ToPointer(); int stride = srcData.Stride; byte* p; 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 r1, r2, r3, r4, r5, r6, r7, r8, r0; int g1, g2, g3, g4, g5, g6, g7, g8, g0; int b1, b2, b3, b4, b5, b6, b7, b8, b0; float 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 + stride + 3; r8 = p[2]; g8 = p[1]; b8 = p[0]; p = pIn; r0 = p[2]; g0 = p[1]; b0 = p[0]; vR = (float)r0 - (float)(r1 + r2 + r3 + r4 + r5 + r6 + r7 + r8) / 8; vG = (float)g0 - (float)(g1 + g2 + g3 + g4 + g5 + g6 + g7 + g8) / 8; vB = (float)b0 - (float)(b1 + b2 + b3 + b4 + b5 + b6 + b7 + b8) / 8; vR = r0 + vR * val; vG = g0 + vG * val; vB = b0 + vB * val; 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; } } b.UnlockBits(srcData); bmprtn.UnlockBits(dstData); return bmprtn; } catch { return null; } }