Search code examples
c#opencvtype-conversionemgucv

How to convert OpenCvSharp.Mat to Emgu.CV.Mat?


I'm using OpenCVSharp for image processing, but now I also need some of the features of Emgu CV to detect faces in my images.

I have the following minimal example:

public static void DetectFace(OpenCvSharp.Mat inputImage) {
    var faceDetector = new Emgu.CV.FaceDetectorYN("myTrainingModel", "", new Size(inputImage.Width, inputImage.Height));
    var emguMat = new Emgu.CV.Mat();
    faceDetector.Detect(inputImage, emguMat); // <-- gives error: Argument 1: cannot convert from 'OpenCvSharp.Mat' to 'Emgu.CV.IInputArray'

    // ... more code
}

The error I get is:

Argument 1: cannot convert from 'OpenCvSharp.Mat' to 'Emgu.CV.IInputArray'

I know the error I get could be solved by converting an OpenCvSharp.Mat to an Emgu.CV.IInputArray, however I would rather like to know how to convert an OpenCvSharp.Mat to an Emgu.CV.Mat. As an Emgu.CV.Mat implements the Emgu.CV.IInputArray interface and I'm going to need to be able to convert to Emgu.CV.Mat later in my code anyway.


Solution

  • I found the following solution that worked, thanks to wingsziye for sharing.

    public static void DetectFace(OpenCvSharp.Mat inputImage) {
        var faceDetector = new Emgu.CV.FaceDetectorYN("myTrainingModel", "", new Size(inputImage.Width, inputImage.Height));
        var emguMat = new Emgu.CV.Mat();
    
        // Create an Emgu Mat for the input parameter
        var emguInputImage = new Emgu.CV.Mat();
    
        // Load the OpenCvSharp.Mat into the new Emgu Mat.
        Emgu.CV.CvInvoke.Imdecode(inputImage.ToBytes(), Emgu.CV.CvEnum.ImreadModes.AnyColor, emguInputImage );
        
        // running face detection on the new Emgu Mat.
        faceDetector.Detect(emguInputImage , emguMat);
    
        // ... more code
    }