首页 > 编程语言 > C#中OpenCVSharp实现轮廓检测
2020
11-19

C#中OpenCVSharp实现轮廓检测

OpenCv提供了函数 findContours()用于对物体轮廓进行检测,该函数实现算法是由S.suzuki K.Abe于1985年发表的。OpenCVSharp封装了这个函数,有2个参数(contours,hierarchy)要做特别的说明。

public static void FindContours(InputOutputArray image, out Point[][] contours,
out HierarchyIndex[] hierarchy, RetrievalModes mode, 
ContourApproximationModes method, Point? offset = null);

解析:contours 的类型是Point[][],它相当于OpenCV中的Vector<Vector<Point>> contours,存储多个轮廓,每个轮廓是由若干个点组成,可以在该函数前声明Point[][] contours;,在C#中没有赋值的变量在用的时候是不允许的,因为它是输出的结果,可以不需要给它new空间,但必须在函数的参数中声明是out;参数hierarchy为包含图像拓扑结构的信息,它是HierarchyIndex[]类型,这是输入的结果,同样要在函数的参数中声明为out。具体代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;
using OpenCvSharp.Extensions;
namespace OpenCvSharp_03
{
  class Program
  {

    static void Main(string[] args)
    {
      
      Mat srcImage = Cv2.ImRead(@"D:\MyData\circle.jpg");     
      Mat dst_Image = MyFindContours(srcImage);
      Cv2.ImShow("srcImage:", srcImage);
      Cv2.ImShow("contours", dst_Image);
      Cv2.WaitKey();

    }
    public static Mat MyFindContours(Mat srcImage)
    {
      //转化为灰度图
      Mat src_gray = new Mat();
      Cv2.CvtColor(srcImage, src_gray, ColorConversionCodes.RGB2GRAY);

      //滤波
      Cv2.Blur(src_gray, src_gray, new Size(3, 3));

      //Canny边缘检测
      Mat canny_Image = new Mat();
      Cv2.Canny(src_gray, canny_Image, 100, 200);

      //获得轮廓
      Point[][] contours;
      HierarchyIndex[] hierarchly;          
      Cv2.FindContours(canny_Image,out contours,out hierarchly, RetrievalModes.Tree,ContourApproximationModes.ApproxSimple,new Point(0,0));

      //将结果画出并返回结果
      Mat dst_Image = Mat.Zeros(canny_Image.Size(),srcImage.Type());
      Random rnd = new Random();
      for (int i = 0; i < contours.Length; i++)
      {
        Scalar color = new Scalar(rnd.Next(0,255),rnd.Next(0,255),rnd.Next(0,255));
        Cv2.DrawContours(dst_Image, contours, i, color, 2,LineTypes.Link8, hierarchly);
      }
      return dst_Image;
    }
  }
}

我封装好了MyFindContours()这个函数,方便大家调用进行测试

测试结果如下:

ysnshi

这是轮廓的结果图

到此这篇关于C#中OpenCVSharp实现轮廓检测的文章就介绍到这了,更多相关C# OpenCVSharp轮廓检测内容请搜索自学编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持自学编程网!

编程技巧