在opencvsharp中很多api的写法跟c++中有所不同不同,比如在霍夫直线检测Cv2.HoughLinesP这个api中返回的是一个LineSegmentPoint[],而非一个Vec4i的数组;
所以首先创建一个LineSegmentPoint类型的数组作为接收,再调用Cv2.HoughLinesP这个函数
HoughLines(InputArray image, double rho, double theta, int threshold, double srn = 0, double stn = 0);
LineSegmentPoint[] lineSegmentPoint; //创建接收数组
lineSegmentPoint = Cv2.HoughLinesP(gray, 1.0, Cv2.PI/180,200,100,300);//进行霍夫变换直线检测
在数组LineSegmentPoint[]中可以打印下可以看到每个数组的元素其实是包含线段的两个端点,这样就可以画出直线
for (int i = 0; i < lineSegmentPoint.Length; i++)
{
Console.WriteLine(lineSegmentPoint[i].P1);
Console.WriteLine(lineSegmentPoint[i].P2);
Console.WriteLine();
}
打印结果:
(x:35 y:126)
(x:54 y:483)
(x:37 y:124)
(x:298 y:128)
(x:611 y:429)
(x:616 y:137)
(x:72 y:483)
(x:612 y:427)
(x:403 y:129)
(x:610 y:129)
接下来再将数组中的所有元素绘制成线段就可以看到结果:
Cv2.CvtColor(gray, gray, ColorConversionCodes.GRAY2BGR);
for (int i = 0; i < lineSegmentPoint.Length; i++)
{
Cv2.Line(gray, lineSegmentPoint[i].P1, lineSegmentPoint[i].P2, Scalar.RandomColor(), 3);
}
下面是一个实例:
Mat src = new Mat(@"D:\BaiduNetdiskDownload\电视.jpg", ImreadModes.Color);
Cv2.PyrDown(src, src);
Cv2.Resize(src, src, new Size(src.Width / 3, src.Height / 3));//or
//Cv2.Resize(src, src, new Size(0, 0), 1.0f / 3.0f, 1.0f / 3.0f);
Cv2.ImShow("src", src);
Mat gray = new Mat();
Cv2.CvtColor(src, gray, ColorConversionCodes.BGR2GRAY);
Cv2.Threshold(gray, gray, 100, 255, ThresholdTypes.Binary);//二值化
Mat stElem = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(7, 7));
Cv2.MorphologyEx(gray, gray, MorphTypes.Open, stElem, new Point(-1, -1), 3);//来三次次开操作把无关点滤掉
Cv2.MorphologyEx(gray, gray, MorphTypes.Dilate, stElem);//膨胀扩大下范围
Cv2.ImShow("binary", gray);
Cv2.Canny(gray, gray, 20, 50,3);
//Cv2.CvtColor(gray, gray, ColorConversionCodes.GRAY2BGR);
LineSegmentPoint[] lineSegmentPoint;
lineSegmentPoint = Cv2.HoughLinesP(gray, 1.0, Cv2.PI/180,200,100,300);
for (int i = 0; i < lineSegmentPoint.Length; i++)
{
Console.WriteLine(lineSegmentPoint[i].P1);
Console.WriteLine(lineSegmentPoint[i].P2);
Console.WriteLine();
}
Cv2.CvtColor(gray, gray, ColorConversionCodes.GRAY2BGR);
for (int i = 0; i < lineSegmentPoint.Length; i++)
{
Cv2.Line(gray, lineSegmentPoint[i].P1, lineSegmentPoint[i].P2, Scalar.RandomColor(), 3);
}
Cv2.ImShow("dst", gray);
Cv2.WaitKey();