[函數名稱]html
Hough 變換直線檢測 HoughLineDetect(WriteableBitmap src, int threshould)算法
[算法說明]函數
Hough變換是數字圖像處理中一種經常使用的幾何形狀識別方法,它能夠識別直線,圓,橢圓,弧線等spa
等幾何形狀,其基本原理是利用圖像二維空間和Hough參數空間的點-線對偶性,把圖像空間中的形.net
狀檢測問題轉換到Hough的參數空間中去,最終以尋找參數空間中的峯值問題,獲得形狀檢測的最優code
結果。orm
/// <summary> /// Hough transform of line detectting process. /// </summary> /// <param name="src">The source image.</param> /// <param name="threshould">The threshould to adjust the number of lines.</param> /// <returns></returns> public static WriteableBitmap HoughLineDetect(WriteableBitmap src, int threshould)////2 Hough 變換直線檢測 { if (src != null) { int w = src.PixelWidth; int h = src.PixelHeight; WriteableBitmap srcImage = new WriteableBitmap(w, h); byte[] temp = src.PixelBuffer.ToArray(); int roMax = (int)Math.Sqrt(w * w + h * h) + 1; int[,] mark = new int[roMax, 180]; double[] theta = new double[180]; for (int i = 0; i < 180; i++) { theta[i] = (double)i * Math.PI / 180.0; } double roValue = 0.0; int transValue=0; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { if (temp[x * 4 + y * w*4] == 0) { for (int k = 0; k < 180; k++) { roValue = (double)x * Math.Cos(theta[k]) + (double)y * Math.Sin(theta[k]); transValue = (int)Math.Round(roValue / 2 + roMax / 2); mark[transValue, k]++; } } } } for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { int T = x * 4 + y * w * 4; if (temp[T] == 0) { for (int k = 0; k < 180; k++) { roValue = (double)x * Math.Cos(theta[k]) + (double)y * Math.Sin(theta[k]); transValue = (int)Math.Round(roValue / 2 + roMax / 2); if (mark[transValue, k] > threshould) { temp[T + 2] = (byte)255; } } } } } Stream sTemp = srcImage.PixelBuffer.AsStream(); sTemp.Seek(0, SeekOrigin.Begin); sTemp.Write(temp, 0, w * 4 * h); return srcImage; } else { return null; } } <strong><span style="font-size:14px;">[圖像效果]</span></strong>
注意:圖中沒有標紅的線,是由於threshold=80,若是這個值改變,會影響檢測結果,這個值足夠小,另外兩條直線也將被標紅。
htm