///////////////////////// // Convultion Filters // /////////////////////// static public byte[] ApplyKernel(byte[] buffer, int stride, CustomKernel customKernel) { double[,] kernel = customKernel.GetKernel(); byte[] result = new byte[buffer.Length]; // 1D Bitmap byte data for (int i = 0; i < buffer.Length; i++) { if ((i + 1) % 4 == 0) { result[i] = buffer[i]; continue; } double newByte = 0; bool ignorePixel = false; // Kernel Columns int lowerColBound = -kernel.GetLength(0) / 2 - customKernel.anchor.X; int upperColBound = kernel.GetLength(0) / 2 - customKernel.anchor.X; for (int j = lowerColBound; j <= upperColBound; j++) { if ((i + 4 * j < 0) || (i + 4 * j >= buffer.Length) || ignorePixel) { newByte = 0; break; } // Kernel Rows int lowerRowBound = -kernel.GetLength(1) / 2 - customKernel.anchor.Y; int upperRowBound = kernel.GetLength(1) / 2 - customKernel.anchor.Y; for (int k = lowerRowBound; k <= upperRowBound; k++) { if ((i + 4 * j + k * stride < 0) || (i + 4 * j + k * stride >= buffer.Length)) { ignorePixel = true; break; } newByte += kernel[ j - lowerColBound, k - lowerRowBound] * buffer[i + 4 * j + k * stride] + customKernel.offset; } } result[i] = (byte)(newByte < 0 ? 0 : newByte > 255 ? 255 : newByte); } return(result); }
public void SetUpKernelEditor() { Console.WriteLine(kernel); CustomKernel customKernel = Kernel.customKernels[kernel]; CBFilterType.DataSource = filterTypes; NUDDivisor.Minimum = decimal.MinValue; NUDDivisor.Maximum = decimal.MaxValue; NUDDivisor.Value = customKernel.divisor; NUDKernelColumn.Value = customKernel.kernel.GetLength(0); NUDKernelRow.Value = customKernel.kernel.GetLength(1); NUDOffset.Value = customKernel.offset; NUDAnchorCol.Value = customKernel.anchor.X; NUDAnchorRow.Value = customKernel.anchor.Y; SetUpTableLayout(customKernel.kernel.GetLength(0), customKernel.kernel.GetLength(1), customKernel.kernel); }
static public Bitmap ApplyFilter(this Bitmap bmp, Func <byte[], int, CustomKernel, byte[]> filter, CustomKernel customKernel) { byte[] buffer = bmp.GetBitmapDataBytes(out int stride); byte[] result = filter(buffer, stride, customKernel); Bitmap bmpRes = new Bitmap(bmp.Width, bmp.Height); bmpRes.SetBitmapDataBytes(result); return(bmpRes); }