EmguCV环境配置:
Emgu CV4图像处理之环境搭建1(C#)_emgucv 4.7-CSDN博客
本文测试环境:
win10 64位
vistual studio 2019
Emgu CV 4.6.0
环境配置准备:
1 新增控制台项目,.net framework为4.7.2
2 把win-x64目录的native目录下的文件全部拷贝到项目的运行目录Debug目录下
3 项目选择x64
4 添加项目引用Emgu.CV.dll、Emgu.CV.Platform.NetFramework.dll、System.Drawing.dll和System.Runtime.InteropServices.RuntimeInformation.dll
代码如下:
static void ReadMultiBarCode3(string imageFileName)
{
Emgu.CV.Mat mat = Emgu.CV.CvInvoke.Imread(imageFileName);
Mat gray_srvPic = new Mat();
Emgu.CV.CvInvoke.CvtColor(mat, gray_srvPic, Emgu.CV.CvEnum.ColorConversion.Bgr2Gray);
//compute the Scharr gradient magnitude representation of the images
//in both the x and y direction using OpenCV 2.4
IOutputArray dstX = new Mat();
IOutputArray dstY = new Mat();
Emgu.CV.CvInvoke.Sobel(gray_srvPic, dstX, DepthType.Cv32F, 1, 0, -1);
Emgu.CV.CvInvoke.Sobel(gray_srvPic, dstY, DepthType.Cv32F, 0, 1, -1);
//subtract the y-gradient from the x-gradient
IOutputArray gradient = new Mat();
Emgu.CV.CvInvoke.Subtract(dstX, dstY, gradient);
Emgu.CV.CvInvoke.ConvertScaleAbs(gradient, gradient,1,0);
IOutputArray gradientDst1 = new Mat();
Emgu.CV.CvInvoke.Blur(gradient, gradientDst1, new Size(9, 9),new Point(-1,-1));
IOutputArray gradientDst2 = new Mat();
Emgu.CV.CvInvoke.Threshold(gradientDst1, gradientDst2, 100, 255, ThresholdType.Binary);
IOutputArray kernel = new Mat();
kernel=Emgu.CV.CvInvoke.GetStructuringElement(ElementShape.Rectangle, new Size(3, 3), new Point(-1,-1));
IInputOutputArray closed = new Mat();
//closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
Emgu.CV.CvInvoke.MorphologyEx(gradientDst2, closed, MorphOp.Close, kernel, new Point(-1,-1), 1, BorderType.Default, new MCvScalar());
//# perform a series of erosions and dilations
//closed = cv2.erode(closed, None, iterations = 4)
Emgu.CV.CvInvoke.Erode(closed, closed, null, new Point(-1, -1), 1, BorderType.Default, new MCvScalar());
//closed = cv2.dilate(closed, None, iterations = 4)
Emgu.CV.CvInvoke.Dilate(closed, closed, null, new Point(-1, -1), 1, BorderType.Default, new MCvScalar());
//Mat element = CvInvoke.GetStructuringElement(Emgu.CV.CvEnum.ElementShape.Rectangle, new Size(3, 3), new Point(-1, -1));
//CvInvoke.Dilate(closed, closed, element, new Point(-1, -1), 4, Emgu.CV.CvEnum.BorderType.Default, new MCvScalar());
//cnts = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL,
// cv2.CHAIN_APPROX_SIMPLE)
IOutputArray output1 = new Mat();
VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint();
VectorOfRect hierarchy = new VectorOfRect();
//查找轮廓
CvInvoke.FindContours(closed, contours, hierarchy, Emgu.CV.CvEnum.RetrType.External, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);
CvInvoke.Polylines(mat, contours, true, new MCvScalar(0, 255, 0), 5);
CvInvoke.Imshow("after_pic", mat);
CvInvoke.WaitKey(0);
}
主程序测试:
static void Main(string[] args)
{
ReadMultiBarCode3("test.png");
Console.ReadLine();
}
test.png图片如下:
运行结果如下: