emgu cv 輪廓提取
阿新 • • 發佈:2019-01-03
第一步:
建c#窗體
新增好COM和引用
在窗體上新增兩個picturebox 控制元件和一個按鍵
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Emgu.CV; using Emgu.CV.Structure; using Emgu.Util; namespace lunkuo { public partial class Form1 : Form { static string filename; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { OpenFileDialog open = new OpenFileDialog(); if (open.ShowDialog() == DialogResult.OK) { filename = open.FileName; pictureBox1.Load(filename); Image<Gray, byte> src = new Image<Gray, byte>(open.FileName); test(src); } } private void test(Image<Gray, byte> src) { CvInvoke.cvThreshold(src, src, 50, 250, Emgu.CV.CvEnum.THRESH.CV_THRESH_OTSU); Image<Gray, byte> dst = new Image<Gray, byte>(src.Size);//儲存最終結果影象 IntPtr Dyncontour = new IntPtr();//存放檢測到的影象塊的首地址 IntPtr Dynstorage = CvInvoke.cvCreateMemStorage(0);//開闢記憶體區域 int m; m = 88;//在不安全處理下獲取的資料 int n = CvInvoke.cvFindContours(src, Dynstorage, ref Dyncontour, m, Emgu.CV.CvEnum.RETR_TYPE.CV_RETR_LIST, Emgu.CV.CvEnum.CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_NONE, new Point(1, 1)); Seq<Point> DyncontourTemp1 = new Seq<Point>(Dyncontour, null);//方便對IntPtr型別進行操作 Seq<Point> DyncontourTemp = DyncontourTemp1; for (; DyncontourTemp1 != null && DyncontourTemp1.Ptr.ToInt32() != 0; DyncontourTemp1 = DyncontourTemp1.HNext) { CvInvoke.cvDrawContours(dst, DyncontourTemp1, new MCvScalar(128, 128, 128), new MCvScalar(255, 255, 255), 0, 1, Emgu.CV.CvEnum.LINE_TYPE.CV_AA, new Point(0, 0)); } pictureBox2.Image = dst.ToBitmap(); } } }
結果如圖所示:
void cvDrawContours( CvArr *img, CvSeq* contour, CvScalar external_color,
CvScalar hole_color, int max_level, int thickness=1, int line type=8 );
cvDrawContours函式在影象上畫出輪廓,其中external_color指定外圍輪廓的顏色,hole_color指定內部輪廓的顏色(孔),max_level是一個比較關鍵的引數,也比較難理解,它指定被畫的輪廓的最大層數,等於0時只畫出第一個輪廓,等於1時畫出第一個輪廓以及在它後面的同一層所有的輪廓,等於