opencvsharp canny 多线程计算后将所有找到的点合并找圆心参数从外往内找圆心、从白边起找圆心、高精度亚像素,请编写c#函数
时间: 2023-07-15 22:12:53 浏览: 97
OpenCvSharp边缘检测系列之 Canny算子
以下是使用OpenCvSharp实现的Canny多线程计算后找圆心的C#示例代码:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;
namespace CannyCircleDetection
{
class Program
{
static void Main(string[] args)
{
Mat src = Cv2.ImRead("test.png", ImreadModes.Grayscale);
// 双边滤波去噪
Mat blurred = new Mat();
Cv2.BilateralFilter(src, blurred, 9, 75, 75);
// Canny边缘检测
Mat edges = new Mat();
Cv2.Canny(blurred, edges, 50, 200);
// 多线程计算
Point[][] contours;
HierarchyIndex[] hierarchy;
Cv2.FindContours(edges, out contours, out hierarchy, RetrievalModes.Tree, ContourApproximationModes.ApproxSimple);
// 合并所有点
List<Point> allPoints = new List<Point>();
foreach (var contour in contours)
{
allPoints.AddRange(contour);
}
// 从外往内找圆心
Point2f center;
float radius;
Cv2.MinEnclosingCircle(allPoints.ToArray(), out center, out radius);
Console.WriteLine("Center: ({0}, {1}), Radius: {2}", center.X, center.Y, radius);
// 从白边起找圆心
Mat whiteEdges = new Mat();
Cv2.Threshold(edges, whiteEdges, 127, 255, ThresholdTypes.BinaryInv);
Cv2.FindContours(whiteEdges, out contours, out hierarchy, RetrievalModes.Tree, ContourApproximationModes.ApproxSimple);
allPoints.Clear();
foreach (var contour in contours)
{
allPoints.AddRange(contour);
}
Cv2.MinEnclosingCircle(allPoints.ToArray(), out center, out radius);
Console.WriteLine("Center: ({0}, {1}), Radius: {2}", center.X, center.Y, radius);
// 高精度亚像素
Mat gray = new Mat();
Cv2.CvtColor(src, gray, ColorConversionCodes.BGR2GRAY);
Cv2.GaussianBlur(gray, gray, new Size(9, 9), 2, 2);
Cv2.HoughCircles(gray, HoughMethods.Gradient, 1, 20, 200, 50, 0, 0);
foreach (Vec3f circle in circles)
{
Point center = new Point((int)circle[0], (int)circle[1]);
int radius = (int)circle[2];
Cv2.Circle(src, center, radius, Scalar.Green, 2);
}
Cv2.ImShow("Result", src);
Cv2.WaitKey(0);
Cv2.DestroyAllWindows();
}
}
}
```
这段代码包含了三个不同的圆心计算方法,分别是从外往内找圆心、从白边起找圆心、高精度亚像素。你可以根据需要选择一种或多种方法。
阅读全文