使用 FindContours() 方法 來查找圖像的邊緣信息.是一個基本的聯系.
在OpenCvSharp中所有的 FindXXX() 方法 . 都需要開辟一開內存來儲存結果使用 CvMesStorage storage = new CvMemStorage() 來開辟. 返回的都是一個CvSeq 序列. CvSeq<CvPoint> contours = new CvSeq<CvPoint>(SeqType.Contour,storage); 也就是這個內存塊中裝的是這個結果序列.
最后. 我們使用 DrawContours(CvSeq contours,color 外框顏色 ,Color 內框顏色,int 線條寬). 來將邊緣畫出.
View Code
1 using System;
2 using OpenCvSharp;
3
4 namespace CVS231
5 {
6 // 練習 使用FindContours 方法來查找輪廓
7 public class Program
8 {
9 static void Main()
10 {
11 using(CvCapture cap = CvCapture.FromCamera(1))
12 using(CvWindow win = new CvWindow("CVS231"))
13 {
14 while (Cv.WaitKey(10) < 0) {
15 // 得到視頻截圖
16 using (IplImage src = cap.QueryFrame())
17 // 創建一個同等大小的 Canny圖
18 using(IplImage cannyImg = new IplImage(src.Size,BitDepth.U8,1))
19 // ***所有FindXXX() 方法.都需要開辟一塊內存來存儲查找到的輪廓信息
20 using (CvMemStorage storage = new CvMemStorage())
21 {
22 // 將視頻延Y軸反轉.這樣,視頻里的圖像不會是反的. 效果與照鏡子一樣.
23 src.Flip(src,FlipMode.Y);
24 // 用原始圖生成Canny圖像
25 src.CvtColor(cannyImg, ColorConversion.BgrToGray);
26 Cv.Canny(cannyImg,cannyImg,50,120);
27
28 // 創建一個序列來存放所找到的輪廓
29 CvSeq<CvPoint> contours = new CvSeq<CvPoint>(SeqType.Contour,storage);
30 // ** 使用 FindContours 方法 來在Canny圖像中查找輪廓. 返回一個Int值 .是找到的輪廓個數
31 int num = Cv.FindContours(cannyImg,storage,out contours);
32 // 使用圖像的 DrawContours方法來把這些輪廓畫出來,
33 // 在畫之前需要判斷下是否查找到輪廓. 找到再畫. 沒找到就畫會出錯的.
34 if (num > 0) {
35 src.DrawContours(contours,new CvColor(0,255,0),new CvColor(0,0,255),1);
36 // 這個 DrawContours 方法 在Cv下面也有.跟Flip一個 Cv.DrawContours() 不過他的第一個參數
37 // 需要告訴畫在哪個IplImage上.
38 }
39 // 將結果顯示到 窗口上.
40 win.Image = src;
41 }
42 }
43 }
44 }
45 }
46 }
運行結果:

