用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();
}
}
}
}