OpenCVSharp 4.5 Hough变换检测直线

该博客演示了如何利用OpenCVSharp库在C#中实现OpenCV的Hough线变换,包括标准Hough线变换和概率Hough线变换。通过处理图像并绘制检测到的线条,展示了这两种方法在图像处理中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用OpenCVSharp跑一遍OpenCV官方教程

官方OpenCV教程链接:https://docs.opencv.org/4.5.0/d9/db0/tutorial_hough_lines.html

核心函数: HoughLines()HoughLinesP() 

using System;
using OpenCvSharp;

namespace ConsoleApp1
{
    class tutorial15 : ITutorial
    {
        public void Run()
        {

            using (Mat src = new Mat("I:\\csharp\\images\\sudoku.png", ImreadModes.Color))
            using (Mat dst = new Mat())
            using(Mat cdst = new Mat())
            {
                Cv2.Canny(src, dst, 50, 200, 3);
                // Copy edges to the images that will display the results in BGR
                
                Cv2.CvtColor(dst, cdst, ColorConversionCodes.GRAY2BGR);
                Mat cdstP = cdst.Clone();

                // Standard Hough Line Transform                            
                LineSegmentPolar[] lines = Cv2.HoughLines(dst, 1, Cv2.PI / 180, 150, 0, 0); // runs the actual detection
                                                                                 // Draw the lines
                for (int i = 0; i < lines.Length; i++)
                {
                    float rho = lines[i].Rho, theta = lines[i].Theta;
                    Point pt1, pt2;
                    double a = Math.Cos(theta), b = Math.Sin(theta);
                    double x0 = a * rho, y0 = b * rho;
                    pt1.X = (int)Math.Round(x0 + 1000 * (-b));
                    pt1.Y = (int)Math.Round(y0 + 1000 * (a));
                    pt2.X = (int)Math.Round(x0 - 1000 * (-b));
                    pt2.Y = (int)Math.Round(y0 - 1000 * (a));
                    Cv2.Line(cdst, pt1, pt2, new Scalar(0, 0, 255), 3, LineTypes.AntiAlias);
                }
                // Probabilistic Line Transform
                LineSegmentPoint[] linesP = Cv2.HoughLinesP(dst,1, Cv2.PI / 180, 50, 50, 10); // runs the actual detection
                                                                      // Draw the lines
                for (int i = 0; i < linesP.Length; i++)
                {                    
                    Cv2.Line(cdstP, linesP[i].P1, linesP[i].P2, new Scalar(0, 0, 255), 3, LineTypes.AntiAlias);
                }
                // Show results
                using(new Window("Source",src))
                using( new Window("Detected Lines(in red) - Standard Hough Line Transform", cdst))
                using (new Window("Detected Lines (in red) - Probabilistic Line Transform", cdstP))
                    Window.WaitKey();
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值