OpenCVSharp 大圖找小圖


最近做缺口圖登錄驗證碼破解,需要識別到缺口圖片的位置,圖片如下:

 

 

 

 

 

 

 使用 OpenCVSharp 來識別。

准備工作如下:

1.下載OpenCV 4.x,解壓並配置好環境變量

2.Nuget 導入 OpenCvSharp4 相關包

using OpenCvSharp;
using (Mat refMat = new Mat("Data/Image/2.png"))//大圖
  using (Mat tplMat = new Mat("Data/Image/1.png"))//小圖
            using (Mat res = new Mat(refMat.Rows - tplMat.Rows + 1, refMat.Cols - tplMat.Cols + 1, MatType.CV_32FC1))
            {
                //Convert input images to gray
                Mat gref = refMat.CvtColor(ColorConversionCodes.BGR2GRAY);
                Mat gtpl = tplMat.CvtColor(ColorConversionCodes.BGR2GRAY);

                Cv2.MatchTemplate(gref, gtpl, res, TemplateMatchModes.CCoeffNormed);
                Cv2.Threshold(res, res, 0.8, 1.0, ThresholdTypes.Tozero);
                while (true)
                {
                    double minval, maxval, threshold = 0.8;
                    Point minloc, maxloc;
                    Cv2.MinMaxLoc(res, out minval, out maxval, out minloc, out maxloc);

                    if (maxval >= threshold)
                    {
                        //Setup the rectangle to draw
                        Rect r = new Rect(new Point(maxloc.X, maxloc.Y), new Size(tplMat.Width, tplMat.Height));
                        Console.WriteLine(maxloc.X);
                        //Draw a rectangle of the matching area
                        Cv2.Rectangle(refMat, r, Scalar.LimeGreen, 2);

                        //Fill in the res Mat so you don't find the same area again in the MinMaxLoc
                        Rect outRect;
                        Cv2.FloodFill(res, maxloc, new Scalar(0), out outRect, new Scalar(0.1), new Scalar(1.0));
                    }
                    else
                        break;
                }

                

                Cv2.ImShow("Matches", refMat);
                
                Cv2.WaitKey();
            }

結果如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM