C#中OpenCVSharp實現(xiàn)輪廓檢測
OpenCv提供了函數(shù) findContours()用于對物體輪廓進行檢測,該函數(shù)實現(xiàn)算法是由S.suzuki K.Abe于1985年發(fā)表的。OpenCVSharp封裝了這個函數(shù),有2個參數(shù)(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,存儲多個輪廓,每個輪廓是由若干個點組成,可以在該函數(shù)前聲明Point[][] contours;,在C#中沒有賦值的變量在用的時候是不允許的,因為它是輸出的結果,可以不需要給它new空間,但必須在函數(shù)的參數(shù)中聲明是out;參數(shù)hierarchy為包含圖像拓撲結構的信息,它是HierarchyIndex[]類型,這是輸入的結果,同樣要在函數(shù)的參數(shù)中聲明為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()這個函數(shù),方便大家調(diào)用進行測試
測試結果如下:


到此這篇關于C#中OpenCVSharp實現(xiàn)輪廓檢測的文章就介紹到這了,更多相關C# OpenCVSharp輪廓檢測內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
visio二次開發(fā)--判斷文檔是否已發(fā)生變化(變化就加星號*)
最近做一個故障樹診斷的項目,用visio二次開發(fā),可以同時打開多個繪制的故障樹圖形文檔。項目中需要實現(xiàn)判斷文檔是否發(fā)生變化,這是很多編輯軟件的基本功能,變化了就加個星號*2013-04-04
C#采用mouse_event函數(shù)實現(xiàn)模擬鼠標功能
這篇文章主要介紹了C#模擬鼠標點擊小功能,通過代碼向大家做分析,需要的朋友可以參考下2015-07-07

