} // end of AutoFitThreshold /// <summary> /// 图像灰度变换 /// </summary> /// <param name="b">位图流</param> /// <param name="grayMethod">灰度方法</param> /// <returns></returns> public Bitmap Gray(Bitmap b, GrayMethod grayMethod) { int width = b.Width; int height = b.Height; BitmapData data = b.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); unsafe { byte *p = (byte *)data.Scan0; int offset = data.Stride - width * BPP; byte R, G, B, gray; switch (grayMethod) { case GrayMethod.Maximum: for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { R = p[2]; G = p[1]; B = p[0]; // gray = Max( R, G, B ) gray = (gray = B >= G ? B : G) >= R ? gray : R; p[0] = p[1] = p[2] = gray; p += BPP; } // x p += offset; } // y break; case GrayMethod.Average: for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { R = p[2]; G = p[1]; B = p[0]; // gray = ( R + G + B ) / 3 gray = (byte)((R + G + B) / 3); p[0] = p[1] = p[2] = gray; p += BPP; } // x p += offset; } // y break; case GrayMethod.WeightAveraging: default: for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { R = p[2]; G = p[1]; B = p[0]; // gray = 0.3*R + 0.59*G + 0.11*B gray = (byte)((19661 * R + 38666 * G + 7209 * B) >> 16); p[0] = p[1] = p[2] = gray; p += BPP; } // x p += offset; } // y break; } // switch } b.UnlockBits(data); return(b); } // end of Gray
public static unsafe Bitmap Gray(Bitmap b, GrayMethod grayMethod) { byte R; byte G; byte B; byte gray; int y; int x; int width = b.Width; int height = b.Height; BitmapData data = b.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); byte * p = (byte *)data.Scan0; int offset = data.Stride - (width * 4); switch (grayMethod) { case GrayMethod.Maximum: for (y = 0; y < height; y++) { x = 0; while (x < width) { R = p[2]; G = p[1]; B = p[0]; gray = ((gray = (B >= G) ? B : G) >= R) ? gray : R; p[2] = gray; p[0] = p[1] = gray; p += 4; x++; } p += offset; } break; case GrayMethod.Average: y = 0; while (y < height) { x = 0; while (x < width) { R = p[2]; G = p[1]; B = p[0]; gray = (byte)(((R + G) + B) / 3); p[2] = gray; p[0] = p[1] = gray; p += 4; x++; } p += offset; y++; } break; default: for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { R = p[2]; G = p[1]; B = p[0]; gray = (byte)((((19661 * R) + (38666 * G)) + (7209 * B)) >> 16); p[2] = gray; p[0] = p[1] = gray; p += 4; } p += offset; } break; } b.UnlockBits(data); return(b); }