Applying high pass filter on image in c#
<p>After following <a href="http://fourier.eng.hmc.edu/e161/lectures/gradient/node1.html" rel="nofollow noreferrer">this</a> article, I have come to know that high pass image can be achieved by subtracting low pass image from original image. I am first graying out the image and then applying following filter on the image (as explained in the article).</p>

<pre><code> return new int[,] {{-1, -2, -1},
                    {-2, 12, -2},
                    {-1, -2, -1}};
</code></pre>

<p>Right now just applying this filter, gives me an image detecting edges.</p>

<p>In <a href="http://fourier.eng.hmc.edu/e161/lectures/gradient/node1.html" rel="nofollow noreferrer">this</a> article, it is suggested to <strong>divide it by 16</strong> after applying filter on the image. When I divide that i get an overflow exception and got a negative value to be stored in the image. </p>

<p>I need the following result</p>

<p><a href="https://i.stack.imgur.com/nPGfL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nPGfL.png" alt="enter image description here"></a></p>

<p>But I am getting this result</p>

<p><a href="https://i.stack.imgur.com/b2VMM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b2VMM.png" alt="enter image description here"></a></p>

<p>I need help in this, how can i get the first image.</p>

<p>Usually I divide the result by sum of filter array (in case of blurring the image). </p>

<p>This is the code for applying filter mask on the image..</p>

<pre><code>  public static byte[,] applyFilterMask(byte[,] imageArray, int filterSize, int[,] filterMask, uint width, uint height)
    {
        byte[,] masked2DImage = new byte[height, width];
        for (int row = (filterSize/2) ; row &lt; height - (filterSize/2); row++)
        {
            for (int col = (filterSize / 2); col &lt; width - (filterSize / 2); col++)
            {
                int filterResult = 0;

                // these nested loops are to apply (generic) filter mask
                for (int filterRow = 0; filterRow &lt; filterMask.GetLength(0); filterRow++)
                {
                    for (int filterColumn = 0; filterColumn &lt; filterMask.GetLength(1); filterColumn++)
                    {
                        filterResult += imageArray[row - (filterSize/2) + filterRow, col - (filterSize/2) + filterColumn] * filterMask[filterRow, filterColumn];
                    }
                }

                filterResult = sumOfFilterMask(filterMask) == 0 ? filterResult : (filterResult / sumOfFilterMask(filterMask));
                filterResult = filterResult &gt; 255 ? 255 : (filterResult &lt; 0 ? 0 : filterResult);
                masked2DImage[row, col] = Convert.ToByte(filterResult);
            }
        }       

        return masked2DImage;
    }
</code></pre>