protected static BitmapData GetByteDataFromBitmap(Bitmap bitmap) { if (bitmap != null) { var data = new BitmapData(); var bmData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat); try { var height = bitmap.Height; var width = bitmap.Width; var stride = bmData.Stride; var bytesPerPixel = Image.GetPixelFormatSize(bitmap.PixelFormat) / 8; var offset = stride - width * bytesPerPixel; var totalLength = Math.Abs(stride) * height; var ptr = bmData.Scan0; var rgbValues = new byte[totalLength]; Marshal.Copy(ptr, rgbValues, 0, totalLength); data.UpdateValues(rgbValues, width, height, stride, offset, bytesPerPixel, totalLength); } finally { bitmap.UnlockBits(bmData); } return(data); } return(null); }
protected int MakeConvolutionWithPixel(BitmapData srcData, byte[] dst, int x, int y) { double finalX = 0, finalY = 0; for (var i = 0; i < Kernel1.GetLength(0); i++) { for (var j = 0; j < Kernel1.GetLength(1); j++) { var posI = y + i - 1; var posJ = x + j - 1; var pos = (posI * srcData.Width + posJ) * srcData.BytesPerPixel; finalX += Kernel1[i, j] * srcData.DataBytes[pos]; if (!UseOnlyFirstKernel) { finalY += Kernel2[i, j] * srcData.DataBytes[pos]; } } } var clampedValue = UseOnlyFirstKernel ? (byte)Clamp(Math.Abs(finalX), 0, 255.0) : (byte)Clamp(Math.Sqrt(finalX * finalX + finalY * finalY), 0, 255.0); var currentPixelPos = (y * srcData.Width + x) * srcData.BytesPerPixel; if (clampedValue <= Threshold) { dst[currentPixelPos] = Color.Black.R; dst[currentPixelPos + 1] = Color.Black.G; dst[currentPixelPos + 2] = Color.Black.B; } else { dst[currentPixelPos] = Color.White.R; dst[currentPixelPos + 1] = Color.White.G; dst[currentPixelPos + 2] = Color.White.B; } //dst[currentPixelPos] = clampedValue; //dst[currentPixelPos + 1] = clampedValue; //dst[currentPixelPos + 2] = clampedValue; return(clampedValue > Threshold ? 1 : 0); }