c# opencv 获取多边形中心点

在C#中使用OpenCV获取多边形的中心点,可以按照以下步骤进行:

首先,你需要找到图像中的轮廓。这可以通过FindContours方法实现:

cs 复制代码
using OpenCvSharp;

Mat src = new Mat("your_image_path", ImreadModes.Grayscale);
Mat dst = new Mat();
Cv2.Threshold(src, dst, 0, 255, ThresholdTypes.BinaryInv);

VectorOfVectorPoint contours;
HierarchyIndex[] hierarchy;
Cv2.FindContours(dst, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple);

对于每个找到的轮廓,你可以使用MinAreaRect2方法来找到最小外接矩形,该矩形的中心点通常被用作多边形的中心点:

cs 复制代码
foreach (VectorPoint contour in contours)
{
    RotatedRect rect = Cv2.MinAreaRect(contour);
    Point2f center = rect.Center;
    
    // center now contains the coordinates of the center point of the polygon
    Console.WriteLine($"Center: ({center.X}, {center.Y})");
}

以上代码首先加载一张图像并进行二值化处理,然后找出图像中的所有轮廓。对于每个轮廓,它计算最小外接矩形,并获取该矩形的中心点作为多边形的中心点。请注意,这种方法假设多边形是凸的,对于凹多边形,结果可能不是预期的几何中心。如果你需要处理凹多边形,可能需要使用更复杂的算法来计算其质心或重心。

相关推荐
头发还没掉光光几秒前
C语言贪吃蛇:基于Linux中ncurses库实的贪吃蛇小游戏
linux·c语言·开发语言
海底星光8 分钟前
c#进阶疗法 -自定义鉴权
c#
fie88898 分钟前
基于MATLAB的时变Copula实现方案
开发语言·matlab
冬奇Lab8 分钟前
【Kotlin系列12】函数式编程在Kotlin中的实践:从Lambda到函数组合的优雅之旅
android·开发语言·kotlin
写代码的【黑咖啡】12 分钟前
Python中的Msgpack:高效二进制序列化库
开发语言·python
Jaxson Lin17 分钟前
Java编程进阶:线程基础与实现方式全解析
java·开发语言
xiaoqider18 分钟前
C++继承
开发语言·c++
阿华hhh22 分钟前
day4(IMX6ULL)<定时器>
c语言·开发语言·单片机·嵌入式硬件
FuckPatience23 分钟前
C# .csproj Baseoutputpath/Outputpath、AppendTargetFrameworkToOutputPath
c#
没有bug.的程序员25 分钟前
Java锁优化:从synchronized到CAS的演进与实战选择
java·开发语言·多线程·并发·cas·synchronized·