【问题标题】:Calling an opencv Mat from a dll to windows forms, image is glitchy从dll调用opencv Mat到windows窗体,图像有问题
【发布时间】:2018-02-01 10:36:40
【问题描述】:

我有一个基于 openCv 的 dll,它连接到相机。然后我将cv::mat 对象调用到C# 应用程序中,并将图像显示为图片框对象中的位图。 这可行,但图像偶尔会出现“故障”,每隔几秒就会出现线条闪烁、静电和爆裂声。

有没有办法在显示位图之前检查它是否有效? 当我在 dll 中显示图像时,使用cv::imshow,它看起来很好。

我的代码是:

在 c++ dll 中:

__declspec(dllexport) uchar*  getArucoFrame(void)
{   

        cv::Mat OriginalImg = returnLeftFrame(); // calls the frame from where the camera thread stores it.
        cv::Mat tmp;
        cv::cvtColor(OriginalImg, tmp, CV_BGRA2BGR);
        //if I cv::imshow the Mat here, it looks good.
        return tmp.data;
}

在 C# 方面:

//on a button
 threadImageShow = new Thread(imageShow);
 threadImageShow.Start();

//show image frame in box
private void imageShow()
{
    while(true)
    {
        IntPtr ptr = getArucoFrame();
        if (pictureBoxFrame.Image != null)
        {
            pictureBoxFrame.Image.Dispose();

        }
        Bitmap a = new Bitmap(640, 360, 3 * 640, PixelFormat.Format24bppRgb, ptr);
        pictureBoxFrame.Image = a;
        Thread.Sleep(20);


    }


}

//dll调用

 [DllImport("Vector.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern IntPtr getArucoFrame();

由于图像在 dll 中看起来不错,而在图片框中出现故障,我在调试时遇到了问题。非常感谢任何帮助。谢谢。

【问题讨论】:

    标签: c# c++ winforms opencv picturebox


    【解决方案1】:

    您遇到的问题是您将指向临时图像cv::Mat tmp; 的数据的指针传递给C#,但它在getArucoFrame(void) 的退出时被释放,因此它是悬空指针。它可能有效,但似乎有时会被新数据覆盖。一个最简单但不是最佳的修复方法是将其声明为静态 static cv::Mat tmp;,以便在 DLL 卸载时释放它。

    【讨论】:

    • 谢谢!这几天我一直在扯头发。非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-01
    • 2018-01-23
    • 2013-10-08
    • 1970-01-01
    • 2013-10-10
    • 2012-02-14
    • 1970-01-01
    相关资源
    最近更新 更多