I'm trying to implement a Sobel filter myself.
The result I obtained looks very similar to this (gray):
But not like this (black & white with gradient):
I had tried using threshold but it feels not right:
Is there any method that I can turn the grayscale to the black&white with gradient result?
The following are the steps I use to filter an image in C#:
- Convert a bitmap from a file (already in grayscale)
Convolute each pixel with a Sobel kernel (ex. horizontal)
private static float[][] Sobel3x3Kernel_Horizontal() {
return new float[][] { new float[]{ 1, 2, 1}, new float[]{ 0, 0, 0 }, new float[]{ -1, -2, -1} }; }
Re-map all values to let them fall within the range 0~255 (otherwise there will be negative values or values larger than 255, which can't be used to do Bitmap.SetPixel(int x, int y, Color color)
Output the bitmap result (grayscale)
if (pixel > 255) { pixel = 255; } else if(pixel < 0) { pixel = 0; }
- user8190410