//
// 摘要:
// Performs advanced morphological transformations 形态变换
//
// 参数:
// src:
// Source image
//
// dst:
// Destination image. It will have the same size and the same type as src
//
// op:
// Type of morphological operation 形态运算类型 open、close etc
//
// element:
// Structuring element 结构元素
//
// anchor:
// Position of the anchor within the element. The default value (-1, -1) means that
// the anchor is at the element center
//
// iterations: 迭代次数
// Number of times erosion and dilation are applied. [By default this is 1]
//
// borderType:
// The pixel extrapolation method. [By default this is BorderType.Constant]
//
// borderValue:
// The border value in case of a constant border. The default value has a special
// meaning. [By default this is CvCpp.MorphologyDefaultBorderValue()]
public static void MorphologyEx(InputArray src, OutputArray dst, MorphTypes op, [NullableAttribute(2)] InputArray? element, Point? anchor = null, int iterations = 1, BorderTypes borderType = BorderTypes.Constant, Scalar? borderValue = null);
//GetStructuringElement它是用来决定操作的性质
// 摘要:
// Returns a structuring element of the specified size and shape for morphological 返回形态学的指定大小和形状的结构化元素
// operations. The function constructs and returns the structuring element that
// can be further passed to erode, dilate or morphologyEx.But you can also construct
// an arbitrary binary mask yourself and use it as the structuring element.
//
// 参数:
// shape:
// Element shape that could be one of MorphShapes 元素MorphShapes类型
//矩形:MorphShapes.Rect;交叉形:MorphShapes.Cross; 椭形:MorphShapes.Ellipse;
// ksize:
// Size of the structuring element. 结构元素大小
public static Mat GetStructuringElement(MorphShapes shape, Size ksize);
实现代码
//开运算
OpenCvSharp.Size size = new OpenCvSharp.Size(3, 3);
Mat kerenl = Cv2.GetStructuringElement(MorphShapes.Rect,size);
Cv2.MorphologyEx(s2,dst,MorphTypes.Open,kerenl); //开运算
Cv2.MorphologyEx(s2,dst,MorphTypes.Close,kerenl); //闭运算
Cv2.MorphologyEx(s2,dst,MorphTypes.Gradient,kerenl);//形态学梯度
Cv2.MorphologyEx(s2,dst,MorphTypes.TopHat,kerenl);//顶帽
Cv2.MorphologyEx(s2,dst,MorphTypes.BlackHat,kerenl);//黑帽
形态学操作提取水平和垂直直线
步骤:
Mat s3 = Cv2.ImRead("D:\\OpenCV\\Topencv\\CsharpOpenCv\\CsharpOpenCv\\2.png");
Mat gray3 = new Mat(s3.Size(),s3.Type()) ;
Mat binImage = new Mat(s3.Size(),s3.Type());
Cv2.CvtColor(s3,gray3,ColorConversionCodes.BGR2GRAY);//灰度图像
Cv2.AdaptiveThreshold(gray3,binImage,255,AdaptiveThresholdTypes.MeanC,ThresholdTypes.Binary,15,-2);//二值图像
OpenCvSharp.Size hsize = new OpenCvSharp.Size(s3.Cols / 16, 1);
OpenCvSharp.Size vsize = new OpenCvSharp.Size(1, s3.Rows/16);
Mat hline = Cv2.GetStructuringElement(MorphShapes.Rect,hsize);
Mat vline = Cv2.GetStructuringElement(MorphShapes.Rect,vsize);
Mat tmp = new Mat(s3.Size(),s3.Type());
Mat dst = new Mat(s3.Size(),s3.Type());
Cv2.Erode(binImage,tmp,hline);
Cv2.Dilate(tmp,dst,hline);