c# OpenCvSharp 轮廓检测

c# OpenCvSharp 轮廓检测

using OpenCvSharp;
using OpenCvSharp.Extensions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace app
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 查找轮廓
        /// </summary>
        /// <param name="srcImage"></param>
        /// <returns></returns>
        public static Mat ToolsFindContours(Mat srcImage)
        {
            // 转化为灰度图
            Mat src_gray = new Mat();
            Cv2.CvtColor(srcImage, src_gray, ColorConversionCodes.RGB2GRAY);

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

            // Canny边缘检测
            Mat canny_Image = new Mat();
            // 输入、输出、最小阀值、最大阀值
            Cv2.Canny(src_gray, canny_Image, 100, 200);

            // 获得轮廓
            OpenCvSharp.Point[][] contours;
            HierarchyIndex[] hierarchly;

            /*
            1.寻找轮廓的图像
            2.返回轮廓数组
            3.层次结构索引
            4.轮廓的检索模式(External只检测外轮廓,List检测所有轮廓,CComp检测所有轮廓并建立两个等级,Tree检测所有轮廓并建立等级树
            5.轮廓近似模式(ApproxNone保存物体边界上所有连续的轮廓点, ApproxSimple仅保存轮廓的拐点信息。CV_CHAIN_APPROX_TC89_L1,CV_CHAIN_APPROX_TC89_KCOS使用Teh-Chin chain 近似算法)
            6.Point偏移量,所有的轮廓信息相对于原始图像对应点的偏移量
            */
            Cv2.FindContours(canny_Image, out contours, out hierarchly, RetrievalModes.Tree, ContourApproximationModes.ApproxNone, new OpenCvSharp.Point(0, 0));

            // 将结果画出并返回结果
            Mat dst_Image = Mat.Zeros(canny_Image.Size(), srcImage.Type());

            for (int i = 0; i < contours.Length; i++)
            {
                // 轮廓的颜色为红色
                Scalar color = new Scalar(0, 0, 255);
                /*
                1.输入图
                2.表示输入的轮廓组
                3.指明画第几个轮廓
                4.颜色
                5.thickness为轮廓的线宽,如果为负值或CV_FILLED表示填充轮廓内部
                6.线形
                7.轮廓结构信息
                */
                Cv2.DrawContours(dst_Image, contours, i, color, 2, LineTypes.Link8, hierarchly);
            }
            return dst_Image;
        }

        /// <summary>
        /// 轮廓检测与绘制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnContours_Click(object sender, EventArgs e)
        {
            Mat srcImage = Cv2.ImRead(@"contours.jpg");
            Mat dstImage = ToolsFindContours(srcImage);
            Cv2.ImShow("原图:", srcImage);
            Cv2.ImShow("新图", dstImage);
            Cv2.WaitKey();
        }
    }
}

 

发表回复

您的电子邮箱地址不会被公开。