Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to execute Cython wrapped Python code

I am exporting C++ API for python code using Cython. The application will be executed on Ubuntu. The project files are present here

The function I am wrapping, reads the file name of the image and displays the image. The Show_Img.pyx file looks as follows

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

The c++ interface generated from Cython looks as follows

__PYX_EXTERN_C DL_IMPORT(void) Print_image(char *);

The header file is included in my algo.cpp, which calls the function like below

#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;
}

With the command below, I can also compile the above code and also generate the application

g++ algo.cpp `pkg-config --libs --cflags python-2.7` `pkg-config --libs --cflags opencv` -L. -lShow_Img -o algo

also the path to the library LD_LIBRARY_PATH is set correctly

Upon execution of the application, there is an error Segmentation fault (core dumped)

Why am I unable to execute the application, is there a mistake in the generation process? or Library linking?

like image 509
Bharadwaj Avatar asked Oct 17 '22 17:10

Bharadwaj


1 Answers

To follow up on my comment, You have to call an init function for the module:

// ...
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();
// ...

The reason being is that this sets up the module, include executing the line import cv2. Without it things like accessing the module globals (to get to cv2) won't reliably work. This a likely cause of the segmentation fault.

This is in the documentation example.

like image 94
DavidW Avatar answered Oct 21 '22 02:10

DavidW