如何将 cv::mat 对象从 python 模块传递到 c++ 函数并返回返回的 cv::mat 类型为对象?

How to pass cv::mat objects from a python module to a c++ function and give back returned object which is type cv::mat?

本文关键字:对象 返回 mat cv 函数 类型 c++ python 模块      更新时间:2023-10-16

我尝试用Django启动一个项目,其中一部分是关于显示一些图像。 你可能知道,c++比python快得多。所以我写了一个 c++ 函数,它接收两个 Mat 类型的输入并对它们进行一些预处理,最后返回一个 cv::mat 变量作为输出。

我想在我的 python 模块中调用这个函数,并从我的 python 代码发送两个图像作为输入参数,并在我的 django 项目中显示 c++ 函数的结果。

我尝试用ctypes调用我的c ++函数。CDLL,ctypes 使用简单的函数,但对于此 c++ 代码会给出内存错误。

这是我的 C++ 函数:

extern "C" Mat watermark2(Mat source_img, Mat logo)
{
// Simple watermark
double alpha = 0.5;
int width = logo.size().width;
int height = logo.size().height;
int x_pos = rand() % (source_img.size().width - width);
int y_pos = rand() % (source_img.size().height - height);
cv::Rect pos = cv::Rect(x_pos, y_pos, width, height);
addWeighted(source_img(pos), alpha, logo, 1 - alpha, 0.0, source_img(pos));
return source_img;
}

如您所见,这是一个简单的函数,不会使用大量内存。我测试了一些非常小的图片,我看到了同样的错误。

我在网上搜索了很多,找到了一些关于Wrapping C/C++ for Python的说明。 但我不确定它是否能帮助我。

因为我是 Django 的新手,任何人都可以帮助我如何从我的 python 代码中协商,我有两个带有 c++ 函数的图像来对图像进行一些操作并将返回的输出保存在我的 Django 中?

也许可以考虑使用 Boost-Python 库来连接 Python 和 C++。