无法执行 Cython 包装的 Python 代码
Unable to execute Cython wrapped Python code
我正在使用 Cython 为 python 代码导出 C++ API。该应用程序将在 Ubuntu 上执行。项目文件存在 here
我包装的函数,读取图像的文件名并显示图像。 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
Cython生成的c++接口如下所示
__PYX_EXTERN_C DL_IMPORT(void) Print_image(char *);
头文件包含在我的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;
}
用下面的命令,我也可以编译上面的代码,也可以生成应用程序
g++ algo.cpp `pkg-config --libs --cflags python-2.7` `pkg-config --libs --cflags opencv` -L. -lShow_Img -o algo
库的路径 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();
// ...
原因是这设置了模块,包括执行行import cv2
。没有它,访问模块全局变量(到达 cv2
)之类的事情将无法可靠地工作。这可能是分段错误的原因。
我正在使用 Cython 为 python 代码导出 C++ API。该应用程序将在 Ubuntu 上执行。项目文件存在 here
我包装的函数,读取图像的文件名并显示图像。 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
Cython生成的c++接口如下所示
__PYX_EXTERN_C DL_IMPORT(void) Print_image(char *);
头文件包含在我的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;
}
用下面的命令,我也可以编译上面的代码,也可以生成应用程序
g++ algo.cpp `pkg-config --libs --cflags python-2.7` `pkg-config --libs --cflags opencv` -L. -lShow_Img -o algo
库的路径 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();
// ...
原因是这设置了模块,包括执行行import cv2
。没有它,访问模块全局变量(到达 cv2
)之类的事情将无法可靠地工作。这可能是分段错误的原因。