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

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

相关推荐
睡美人的小仙女12721 小时前
Threejs加载环境贴图报错Bad File Format: bad initial token
开发语言·javascript·redis
rayufo21 小时前
【工具】列出指定文件夹下所有的目录和文件
开发语言·前端·python
RANCE_atttackkk21 小时前
[Java]实现使用邮箱找回密码的功能
java·开发语言·前端·spring boot·intellij-idea·idea
缺点内向1 天前
C#编程实战:如何为Word文档添加背景色或背景图片
开发语言·c#·自动化·word·.net
一起养小猫1 天前
Flutter for OpenHarmony 实战:记账应用数据统计与可视化
开发语言·jvm·数据库·flutter·信息可视化·harmonyos
zhougl9961 天前
Java 所有关键字及规范分类
java·开发语言
java1234_小锋1 天前
Java高频面试题:MyISAM索引与InnoDB索引的区别?
java·开发语言
2501_944525541 天前
Flutter for OpenHarmony 个人理财管理App实战 - 支出分析页面
android·开发语言·前端·javascript·flutter
qq_417129251 天前
C++中的桥接模式变体
开发语言·c++·算法
开源技术1 天前
如何将本地LLM模型与Ollama和Python集成
开发语言·python