OpenCvSharp 轮廓排序:从左到右,从上到下
在 OpenCvSharp 中,可以使用 Cv2.FindContours() 方法找到轮廓,并使用 Cv2.Sort() 方法对轮廓按照指定的方式排序。
要按照从左往右从上往下的顺序排序轮廓,可以使用以下代码:
using OpenCvSharp;
// 读取图像
Mat image = Cv2.ImRead('test.jpg', ImreadModes.GrayScale);
// 找到轮廓
Mat contours = new Mat();
Cv2.FindContours(image, out var hierarchy, contours, RetrievalModes.External, ContourApproximationModes.ApproxSimple);
// 按照左上角坐标排序
Cv2.Sort(contours, SortFlags.SortByLeftmost | SortFlags.SortByTopmost);
// 遍历轮廓并绘制
foreach (var contour in contours)
{
Cv2.DrawContours(image, new[] { contour }, -1, 255, -1);
}
// 显示图像
Cv2.ImShow('Contours', image);
Cv2.WaitKey();
在上面的代码中,使用了 Cv2.Sort() 方法对轮廓进行排序,排序方式为 SortFlags.SortByLeftmost | SortFlags.SortByTopmost,即先按照左边界排序,再按照上边界排序。
排序后,遍历轮廓并绘制即可。
原文地址: https://www.cveoy.top/t/topic/oej9 著作权归作者所有。请勿转载和采集!