[函数名称]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