从 dll 调用 opencv 垫到 Windows 表单,图像出现故障

Calling an opencv Mat from a dll to windows forms, image is glitchy

本文关键字:图像 故障 表单 Windows dll 调用 opencv 垫到      更新时间:2023-10-16

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

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

我拥有的代码是:

在 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 中看起来不错,并且在图片框中出现故障,因此我在调试时遇到问题。任何帮助非常感谢。谢谢。

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