CKVesper7127
CKVesper7127

Reputation: 15

Image Processing: The result of Sobel filter turns out to be gray instead of black and white?

I'm trying to implement a Sobel filter myself.

The result I obtained looks very similar to this (gray):

enter image description here

But not like this (black & white with gradient):

enter image description here

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#:

  1. Convert a bitmap from a file (already in grayscale)
  2. 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} }; }

  3. 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)

  4. Output the bitmap result (grayscale)

Upvotes: 1

Views: 4073

Answers (1)

Cris Luengo
Cris Luengo

Reputation: 60504

To replicate that image you linked from Wikipedia, follow these steps:

  1. Compute the convolution with the Sobel kernel to obtain the x derivative dx.

  2. Compute another convolution to obtain the y derivative dy (transpose the kernel).

  3. These two derivatives together form the gradient (a vector value at each pixel). Determine the magnitude by computing sqrt(dx^2 + dy^2). ^2 here indicates square.

  4. Threshold the result if you want a pure black-and-white result, otherwise scale the result by multiplying it by some value so that the displayed image looks good to you.

Note that what you call the "grayscale image problem" is simply the mapping (your 3rd step) of 0 values to a middle-grey, so that negative values can be shown. This is a correct way of displaying a derivative, as otherwise the negative values would be clipped and hence not visible. These negative values are an important part of the derivative. But this mapping should only be used for display, further computations should always be done on the original values.

Upvotes: 2

Related Questions