0

I have a problem I have been trying to solve, for the past 3 days. Basically I have an app in C# Winforms which captures screenshots, and I need EmguCV to use template matching on those screenshots to find a certain button on a screen. When I use Imread to "import" images this works, but I don't want to save every screenshot. When I try to use template matching, I get this error: Emgu.CV.Util.CvException: OpenCV: (depth == CV_8U || depth == CV_32F) && type == _templ.type() && _img.dims() <= 2 ) and then some more lines to where the error is. I also saw a question on stack overflow with the same error, but it was in OpenCV and in c++ which I don't know. Template matching from a screenshot of a window. Below is an example of my code, which doesn't work.

while(true)
{
    Bitmap bm = new Bitmap(calScreenWidth, calScreenHeight);
    Graphics g = Graphics.FromImage(bm);
    g.CopyFromScreen(0, 0, 0, 0, bm.Size);
    Mat game_img = bm.ToMat();
    Mat button_img = CvInvoke.Imread("gameRetry.JPG", ImreadModes.Unchanged);
    Mat result = new Mat();
    double minVal = 0;
    double maxVal = 0;
    Point maxLoc = new Point();
    Point minLoc = new Point();
    CvInvoke.MatchTemplate(game_img, button_img, result, TemplateMatchingType.CcoeffNormed);
    CvInvoke.MinMaxLoc(result, ref minVal, ref maxVal, ref minLoc, ref maxLoc);
    double threshold = 0.8;

    if (maxVal > threshold)
    {
        Thread.Sleep(1000);
        restartGame();
    }
    game_img.Dispose();
    button_img.Dispose();
    result.Dispose();
    bm.Dispose();
    g.Dispose();
    Thread.Sleep(2000);
}
AGlasencnik
  • 139
  • 1
  • 12
  • so you capture the screen... check the depth and number of channels for the Mat you get from that operation. both needle and haystack have to have the same number of channels ("type" encodes depth and number of channels) -- if that was the issue, please let me know and I'll make an answer out of this – Christoph Rackwitz Mar 11 '22 at 11:01
  • @ChristophRackwitz do you know of an easy method to do so? I am a beginner here. – AGlasencnik Mar 11 '22 at 11:32
  • Mat is an object. it has methods, properties, ... here's a list: https://docs.opencv.org/4.x/d3/d63/classcv_1_1Mat.html -- I have no experience with emgu. if it's just a wrapper around OpenCV, OpenCV's documentation should apply. – Christoph Rackwitz Mar 11 '22 at 12:13
  • @ChristophRackwitz I have found a solution. I had to make both images gray, and now it works – AGlasencnik Mar 11 '22 at 19:05

0 Answers0