【问题标题】:Unable to execute Cython wrapped Python code无法执行 Cython 包装的 Python 代码
【发布时间】:2017-07-07 05:09:55
【问题描述】:

我正在使用 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)

为什么我无法执行应用程序,是生成过程中有错误吗?还是图书馆链接?

【问题讨论】:

  • 您可能必须导入模块。如果你不这样做,全局范围内的东西 (import cv2) 将无法运行。

标签: c++ opencv g++ shared-libraries cython


【解决方案1】:

要跟进我的评论,您必须为模块调用 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)之类的事情将无法可靠地工作。这可能是分段错误的原因。

这是the documentation example

【讨论】:

  • 我尝试在函数内部导入模块cv2,但还是不行,我在cdef public void Print_image(char* name):行后面加了import cv2
  • 关键变化是添加了initShow_Img()。您需要这样做。除了 import cv2 之外,它还做了很多使 Cython 工作所需的事情。
  • 是的,我刚刚意识到,我错过了声明。我太傻了
  • 没问题!小的添加并不总是显而易见的。
  • 嗨,David,我看到您在 Cython 和 Numpy 工具方面进行了大量工作。我目前正在做一个使用大量 Cython 的学生项目,除了 StackOverflow 之外,我还有其他方式可以联系你吗?我绝对相信您的回答会有很大帮助。提前谢谢你
猜你喜欢
  • 2020-09-13
  • 2011-03-04
  • 2017-01-16
  • 1970-01-01
  • 2022-01-22
  • 2017-10-17
  • 1970-01-01
  • 2016-04-28
  • 1970-01-01
相关资源
最近更新 更多