Search code examples
androidgraphicsfilterconvolutionmedian

Android Median Filter using Convolution


I've implemented a basic Sharpen filter using Android convolution as shown (code is Xamarin C#, but java is almost identical):

        private Bitmap Sharpen(Bitmap src, float weight)
    {
        var counter = (weight - 1)/4f*-1f;
        float[] matrixSharpen =
        {
            0, counter, 0,
            counter, weight, counter,
            0, counter, 0
        };
        return CreateBitmapConvolve(src, matrixSharpen);
    }

How can I do something similar, except produce a median (or mean) filter instead of sharpen? I can't seem to find what the matrix configuration should be...


Solution

  • Median filter is not a convolution filter. It is a non-linear filter. As said here (in the slides from The University of Western Ontario Link): enter image description here

    To calculate a median filter, you would have to create your own convolution function and instead of summing the pixels from the neighborhood you would have to take a median from them.

    As to Mean filter the convolution matrix would be (with your counter already applied):

    float[] matrixMean =
            {
                1.0f/9.0f, 1.0f/9.0f, 1.0f/9.0f,
                1.0f/9.0f, 1.0f/9.0f, 1.0f/9.0f,
                1.0f/9.0f, 1.0f/9.0f, 1.0f/9.0f
            };