OpenCV輪廓匹配(C#)

//using OpenCvSharp;
using Emgu.CV;
using Emgu.CV.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //大圖, 比如包含ABC字母的圖
            Mat img = CvInvoke.Imread(@"d:\images\abc.jpg");

            //小圖, 模板圖, 比如包含字母B的圖
            Mat imgB = CvInvoke.Imread(@"d:\images\b.jpg");

            if(img.IsEmpty || imgB.IsEmpty)
            {
                textBox1.Text = "請確認圖像名稱是否正確.";
                return;
            }

            CvInvoke.Resize(imgB, imgB, new Size(), 0.5, 0.5);
            CvInvoke.Imwrite(@"d:\images\b_littile.jpg", imgB);
            CvInvoke.Imshow("B", imgB);
             
            //輪廓提取
            var contoursB = findContours(imgB);
            var  contoursABC = findContours(img);

            //Hu矩計算
            Moments mm2 = CvInvoke.Moments(contoursB[0]);
            Mat hu2 = new Mat();
            CvInvoke.HuMoments(mm2, hu2);

            //輪廓匹配
            for (int n = 0; n < contoursABC.Size; n++)
            {
                Moments mm = CvInvoke.Moments(contoursABC[n]);
                Mat hum = new Mat();
                CvInvoke.HuMoments(mm, hum);

                //Hu矩匹配
                double dist;
                dist = CvInvoke.MatchShapes(hum, hu2, Emgu.CV.CvEnum.ContoursMatchType.I1, 0);
                if (dist < 1)
                {
                    CvInvoke.DrawContours(img, contoursABC, n, new Emgu.CV.Structure.MCvScalar(0, 0, 255), 3,  Emgu.CV.CvEnum.LineType.EightConnected);
                }
            }
            CvInvoke.Imshow("match result", img);
            CvInvoke.WaitKey(0);
            return;
        }

        private VectorOfVectorOfPoint findContours(Mat image  )
        {
            Mat gray = new Mat();  
            Mat binary = new Mat();
            VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint();
            Mat hierarchy = new Mat(); //VectorOfVectorOfInt

            //圖像灰度化
            CvInvoke.CvtColor(image, gray, Emgu.CV.CvEnum.ColorConversion.Bgr2Gray );

            //圖像二值化
            CvInvoke.Threshold(gray, binary, 0, 255, Emgu.CV.CvEnum.ThresholdType.Binary | Emgu.CV.CvEnum.ThresholdType.Otsu);

            //尋找輪廓
            CvInvoke.FindContours(binary, contours, hierarchy, 0, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);
            return contours;
        }


    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章