有時為強化影像之輪廓可以採用"Sobel 邊緣偵測",強化影像邊緣。

 

以3*3的 「遮罩」為例,透過「Spatial Convolution」對整張影像進行處理。

先針對已向進行"Vertical Sobel"強化垂直邊緣,在對影像進行"Horizontal Sobel"強化水平邊緣後將兩張已向合併即可取得完整之邊緣偵測影像。

亦可針對實際應用場景僅採用 Horizontal/Vertical 其中一種。

 

 

針對影像進行"Sobel 邊緣偵測"實驗成果如下圖所示 :

 


C#

private static Bitmap sobel(Bitmap bitmap)
{
    int width = bitmap.Width, height = bitmap.Height;
    int w = 3, h = 3;
    Bitmap dstBitmap = new Bitmap(bitmap);

    byte[,] pix = ImageExtract.getimageArray(bitmap);
    byte[,] resPix = new byte[3, width * height];

    for (int y = 1; y < (height - 1); y++)
    {
        for (int x = 1; x < (width - 1); x++)
        {
            //b,g,r 
            int current = x + (y * width);

            for (int c = 0; c < 3; c++)
            {
                //mask    
                byte[] mask = new byte[w * h];
                for (int my = 0; my < h; my++)
                    for (int mx = 0; mx < w; mx++)
                    {
                        int pos = current + (mx - 1) + ((my - 1) * width);
                        mask[mx + my * w] = pix[c, pos];
                    }

                resPix[c, current] = sobelMask33(mask);
                //resPix[c, current] = pix[c, current];
            }
        }
    }

    ImageExtract.writeImageByArray(resPix, dstBitmap);
    return dstBitmap;
}

private static byte sobelMask33(byte[] gate)
{
    int[] mask1 ={
                    -1,0,1,
                    -2,0,2,
                    -1,0,1
            };

    int[] mask2 ={
                -1,-2,-1,
                0,0,0,
                1,2,1
            };

    int gay1 = 0, gay2 = 0;
    for (int i = 0; i < gate.Length; i++)
    {
        gay1 += (gate[i] * mask1[i]);
        gay2 += (gate[i] * mask2[i]);
    }
    int value = (int)Math.Pow((gay1 * gay1 + gay2 * gay2), 0.5);
    return (byte)((value > 255) ? 255 : value);
}

完整程式碼 : https://github.com/Lung-Yu/ImageToolBox/blob/master/ImageProcessToolBox/Sobel.cs

 

arrow
arrow
    文章標籤
    Image Process space processing
    全站熱搜

    Lung-Yu,Tsai 發表在 痞客邦 留言(1) 人氣()