霍夫直线变换原理及OpenCV直线检测(C#)

原理:
直角坐标系转换为极坐标系
在这里插入图片描述
原点到直线的距离:ρ=xcosɵ+ysinɵ
直线上任意一点代入上述公式均可求出原点到该直线的距离,且为定值

当ɵ与ρ确定时,对应唯一确定直线

遍历目标图像各个像素,带入上述公式绘制绘制ρ和ɵ的正弦关系图像,如下图:
在这里插入图片描述
上图中正弦函数相交于同一点的次数即表示该点对应直线上的有效特征点的个数;

API:

public static LineSegmentPoint[] HoughLinesP(InputArray image, double rho, double theta, int threshold, double minLineLength = 0, double maxLineGap = 0);

在这里插入图片描述
代码实现:

if (fileDialog.ShowDialog() == DialogResult.OK)
       {
    
    

           picFile = fileDialog.FileName;
           inputMat = Cv2.ImRead(picFile, ImreadModes.AnyColor);
           Mat finallyOutMat = inputMat.Clone();
           outMat = new Mat(new Size(inputMat.Cols, inputMat.Rows), inputMat.Type());

           //二值化
           Cv2.Threshold(inputMat, outMat, 90, 255, ThresholdTypes.Binary);

           //提取边缘
           Cv2.Canny(inputMat, outMat, 50, 200);

           var lines = Cv2.HoughLinesP(outMat, 1, Cv2.PI / 180, 100, 90, 60);

           //绘制直线
           Scalar scalar = new Scalar(0, 0, 255);//线的颜色
           for (int i = 0; i < lines.Length; i++)
                {
    
    
                    Cv2.Line(finallyOutMat, lines[i].P1, lines[i].P2, scalar, 4);
                }

           outMat = finallyOutMat.Clone();

           picBox_Display.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(inputMat);
           picBox_After.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(outMat);
       }

在这里插入图片描述

补充说明:
本案例在.NET使用的OpenCV库为OpenCvSharp4

.NET 环境的OpenCv库

猜你喜欢

转载自blog.csdn.net/weixin_40671962/article/details/127253890