轮廓绘制主要用到findcontours和drawcontours,在工程项目中这个功能应该会普遍作为后续功能的基础而被使用,想用opencvsharp做一个圆查找的功能,然后霍夫圆检测的精度貌似不高,在搜索资料后,尝试自己弄一下轮廓绘制,先弄下画轮廓的这部分
要点1:
拓扑结构想要获取全部轮廓用RetrievalModes.Tree, ContourApproximationModes.ApproxNone
要点2:
要在灰度图上显示有颜色的轮廓,要先将灰度图转化为RGB图
程序如下:
Mat src = (Mat)userdata;
Mat a = new Mat();
src.CopyTo(a);
Cv2.Threshold(a, a, 127, 255, ThresholdTypes.Binary);
//Cv2.Canny(a, a, pos*10, 255);
HierarchyIndex[] hierarchy ;
OpenCvSharp.Point[][] coutours;
// 形态学操作
Mat kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(3, 3), new OpenCvSharp.Point(-1, -1));
// 构建形态学操作的结构元
//morphologyEx(binary_img, binary_img, MORPH_CLOSE, kernel, Point(-1, -1));
Cv2.MorphologyEx(a, a, MorphTypes.Close, kernel, new OpenCvSharp.Point(-1, -1));
//闭操作
kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(3, 3), new OpenCvSharp.Point(-1, -1));
// 构建形态学操作的结构元
Cv2.MorphologyEx(a, a, MorphTypes.Open, kernel, new OpenCvSharp.Point(-1, -1));
Cv2.FindContours(a, out coutours, out hierarchy, RetrievalModes.Tree, ContourApproximationModes.ApproxNone);
// int i= hierarchy;
Mat img_rgb = new Mat();
Cv2.CvtColor(a, img_rgb,ColorConversionCodes.GRAY2BGR);
Cv2.DrawContours(img_rgb, coutours, -1,new Scalar(0,255,0),3);
Cv2.ImShow("圆查找", img_rgb);