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})");
}

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

相关推荐
xiaoshuaishuai8几秒前
C# CDN加速与离线包优化PowerSetting慢问题
开发语言·windows·spring·c#
凉辰10 分钟前
解决 H5 键盘遮挡与页面上推
开发语言·javascript·计算机外设
计算机安禾1 小时前
【c++面向对象编程】第25篇:仿函数(函数对象):重载operator()
开发语言·c++·算法
Rust语言中文社区1 小时前
【Rust日报】2026-05-14 Pyrefly v1.0 正式发布:快速的 Python 类型检查器和语言服务器
开发语言·后端·python·rust
kkeeper~1 小时前
0基础C语言积跬步之深入理解指针(4)
c语言·开发语言
周末也要写八哥1 小时前
在C++中使用预定义宏
开发语言·c++·算法
Data_Journal2 小时前
使用Python lxml轻松进行网络爬取
开发语言·php
xcLeigh2 小时前
IoTDB JDBC 完整使用教程:连接、查询、批处理与字符集配置
开发语言·数据库·qt·iotdb·查询·批处理·连接
学会870上岸华师2 小时前
C 语言程序设计——第一章课后编程题
c语言·开发语言·学习·算法
小小编程路2 小时前
新手快速学 Python 极简速成指南
开发语言·c++·python