The type initializer for 'OpenCvSharp.Internal.NativeMethods' threw an exception

Viewed 622

I'm currently working with OpenCVSharp4 for fixing rotated/distorted image.

    public static void FixImagePerspective(string fullPath, PointF[] pointsArray)
    {
        Bitmap srcImg = Image.FromFile(fullPath) as Bitmap;

        var width = srcImg.Width;
        var height = srcImg.Height;

        Mat src = Cv2.ImRead(fullPath);
        var dst = new Mat();

        var dsize = new OpenCvSharp.Size(width, height);
        var srcTri = new Mat(4, 1, MatType.CV_32FC2, pointsArray);
        var dstTri = new Mat(4, 1, MatType.CV_32FC2, new int[] { 0, 0, height, 0, height, width, 0, width });

        var M = Cv2.GetPerspectiveTransform(srcTri, dstTri);

        Cv2.WarpPerspective(src, dst, M, dsize, InterpolationFlags.Linear, BorderTypes.Constant, new Scalar());

        Cv2.ImWrite($"C:\\tmp\\Fixed\\{name}_{count}_corrected.jpg", dst);
    }

This function worked properly from my local machine. But when deployed it into windowsservercore-ltsc2019 Docker container. When ever it come to Cv2.ImRead, it throw the exception that

The type initializer for 'OpenCvSharp.Internal.NativeMethods' threw an exception

I've tried to use dependencies-walker to find the missing *.dll file inside the container and copy it accordingly, but it won't solve the issue. I've also tried to install vc_redist on the docker container but it also didn't solve the issue.

Seem like there is an issue with running OpenCVSharp4 inside docker container. I've already installed OpenCvSharp4.runtime.win packages. But it won't work

I'm using mcr.microsoft.com/dotnet/framework/runtime:4.8-windowsservercore-ltsc2019 for my docker container.

Any tips on how to solve this issue

1 Answers

The root cause is probably some Windows API components that are not present in server core.

As a quick fix you can use the full windows API container mcr.microsoft.com/windows (now replaced by mcr.microsoft.com/server)

Windows container/host compatibility is tricky but I think mcr.microsoft.com/windows:1809 is the equivalent full-API equivalent to your ltsc2019.

Once you have it running you may be able to copy dlls from the full-api container to the servercore container using multiple layers in the dockerfile.

There's an open github issue about a dependency on the Windows Media Framework (not present on Windows Server by default) with a handy list of the dll files that can be copied to resolve the problem...

Related