如何在c++文件中使用opencv函数并将其与Python绑定

How to use opencv functions in C++ file and bind it with Python?

本文关键字:函数 绑定 Python opencv c++ 文件      更新时间:2023-10-16

我想传递一个图像从python脚本到c++代码的opencv计算。为了将两者结合起来,我遵循了这一点。绑定工作得很好,但是当我使用任何opencv内置函数时,它会给我错误。

Traceback(最近一次调用):文件"/home/prashant/Desktop/example.py",第1行导入PBCVT #您的模块,以及您编译的动态库文件的名称(无扩展名)ImportError:/usr/local/lib/python2.7/dist-packages/pbcvt。so: undefined symbol: _ZN2cv8cvtColorERKNS_11_InputArrayERKNS_12_OutputArrayEii

我正在使用opencv 3.1和python 2.7。非常感谢任何帮助/指导。

代码供参考。Python文件。

import pbcvt 
import numpy as np
import cv2
a = cv2.imread("/home/prashant/Documents/opencv-practice/screenshot.png")
c = pbcvt.dot(a)
cv2.imshow("gray image",c)
cv2.waitKey(0)
cv2.destroyAllWindows()
c++代码:

#include <pyboostcvconverter/pyboostcvconverter.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
namespace pbcvt {
using namespace std;
using namespace boost::python;
cv::Mat dot(PyObject *image) {
    cv::Mat matImage, greyMat;
    matImage = pbcvt::fromNDArrayToMat(image);
    cv::cvtColor(matImage, greyMat, CV_BGR2GRAY);
    return greyMat;
}
cv::Mat dot2(cv::Mat leftMat, cv::Mat rightMat) {
    auto c1 = leftMat.cols, r2 = rightMat.rows;
    if (c1 != r2) {
        PyErr_SetString(PyExc_TypeError,
                        "Incompatible sizes for matrix multiplication.");
        throw_error_already_set();
    }
    cv::Mat result = leftMat * rightMat;
    return result;
}

#if (PY_VERSION_HEX >= 0x03000000)
    static void *init_ar() {
#else
    static void init_ar(){
#endif
    Py_Initialize();
    import_array();
    return NUMPY_IMPORT_ARRAY_RETVAL;
}
BOOST_PYTHON_MODULE (pbcvt) {
    //using namespace XM;
    init_ar();
    //initialize converters
    to_python_converter<cv::Mat,
            pbcvt::matToNDArrayBoostConverter>();
    pbcvt::matFromNDArrayBoostConverter();
    //expose module-level functions
    def("dot", dot);
    def("dot2", dot2);
    }
} //end namespace pbcvt

这可能是你必须编辑CMakeLists.txt在第27行find_package(OpenCV COMPONENTS core REQUIRED)和添加更多的组件,如find_package(OpenCV COMPONENTS core imgproc highgui REQUIRED)