首页 > 解决方案 > 如何将 cv::mat 对象从 python 模块传递给 c++ 函数并返回返回的 cv::mat 类型的对象?

问题描述

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

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

我试图用 ctypes.CDLL 调用我的 c++ 函数,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;
}

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

我在网上搜索了很多,发现了一些关于为 Python 包装 C/C++ 的说明。但我不确定它是否能帮助我。

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

标签: c++numpyopencvimage-processingmat

解决方案


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


推荐阅读