Bha*_*waj 5 c++ opencv g++ shared-libraries cython
我正在使用 Cython 为 python 代码导出 C++ API。该应用程序将在 Ubuntu 上执行。项目文件在这里
我正在包装的函数,读取图像的文件名并显示图像。该Show_Img.pyx
文件如下所示
import cv2
cdef public void Print_image(char* name):
img = cv2.imread(name)
cv2.imshow("Image", img)
while(True):
if cv2.waitKey(1) & 0xFF == ord('q'):
break
Run Code Online (Sandbox Code Playgroud)
Cython 生成的 c++ 接口如下所示
__PYX_EXTERN_C DL_IMPORT(void) Print_image(char *);
Run Code Online (Sandbox Code Playgroud)
头文件包含在 my 中algo.cpp
,它调用如下函数
#include<iostream>
#include<Python.h>
#include"Show_Img.h"
using namespace std;
int main(){
char *name = "face.jpg";
Py_Initialize();
Print_image(name);
Py_Finalize();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
使用下面的命令,我也可以编译上面的代码并生成应用程序
g++ algo.cpp `pkg-config --libs --cflags python-2.7` `pkg-config --libs --cflags opencv` -L. -lShow_Img -o algo
Run Code Online (Sandbox Code Playgroud)
库的路径LD_LIBRARY_PATH
也设置正确
执行应用程序时出现错误 Segmentation fault (core dumped)
为什么我无法执行应用程序,是不是生成过程有错误?或图书馆链接?
要跟进我的评论,您必须调用init
该模块的函数:
// ...
Py_Initialize();
initShow_Img(); // for Python3
// (especially with the more modern 2 phase module initialization)
// the process is a little more complicated - see the documentation
Print_image(name);
Py_Finalize();
// ...
Run Code Online (Sandbox Code Playgroud)
原因是这会设置模块,包括执行该行import cv2
。如果没有它,诸如访问模块全局变量(到达cv2
)之类的事情将无法可靠地工作。这可能是分段错误的原因。
这是文档示例中的。