Principle:
The rectangular coordinate system is converted into a polar coordinate system.
The distance from the origin to the straight line: ρ=xcosɵ+ysinɵ.
Substituting any point on the straight line into the above formula can calculate the distance from the origin to the straight line, and it is a fixed value.
When ɵ and ρ are determined, the corresponding unique straight line
Traverse each pixel of the target image, and use the above formula to draw the sinusoidal relationship image between ρ and ɵ, as shown below: The
number of times the sine function intersects at the same point in the above figure represents the number of effective feature points on the corresponding straight line of the point;
API:
public static LineSegmentPoint[] HoughLinesP(InputArray image, double rho, double theta, int threshold, double minLineLength = 0, double maxLineGap = 0);
Code:
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);
}
Additional notes:
The OpenCV library used in .NET in this case is OpenCvSharp4