I'm embedding Python in Qt C++. When I import cv2 in the Python script it crashes with segmentation fault. Running the script in Python works. Running from C++ without Qt works.
Python scrip: works
print("Importing cv2")
import cv2
print("cv2 imported")
C++: works
#include <Python.h>
#include <string>
int main(int argc, char *argv[])
{
std::string module_name("PythonModule");
Py_Initialize();
PyObject* sysPath = PySys_GetObject((char*)"path");
PyObject* pModuleDirPath = PyUnicode_FromString(".");
PyList_Append(sysPath, pModuleDirPath);
Py_DECREF(pModuleDirPath);
PyObject* pModuleName = PyUnicode_FromString(module_name.c_str());
PyObject* pModule = PyImport_Import(pModuleName);
Py_DECREF(pModuleName);
Py_DECREF(pModule);
Py_Finalize();
return 0;
}
Qt: segmentation fault after printing "Importing cv2"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
std::string module_name("PythonModule");
Py_Initialize();
PyObject* sysPath = PySys_GetObject((char*)"path");
PyObject* pModuleDirPath = PyUnicode_FromString(".");
PyList_Append(sysPath, pModuleDirPath);
Py_DECREF(pModuleDirPath);
PyObject* pModuleName = PyUnicode_FromString(module_name.c_str());
PyObject* pModule = PyImport_Import(pModuleName);
Py_DECREF(pModuleName);
Py_DECREF(pModule);
Py_Finalize();
}
.pro file:
LIBS += -L /usr/local/lib/python3.5m -lpython3.5m
INCLUDEPATH += /usr/include/python3.5m
Versions:
Ubuntu 16.04
Python 3.5
opencv-python 3.4.2.17
Qt Creator 4.7.0 Based on Qt 5.11.1
Do anyone recognize this problem?
The problem was that opencv uses Qt as well so a collision occurred.
The solution was to install opencv without Qt support:
pip install opencv-contrib-python-headless
https://pypi.org/project/opencv-contrib-python-headless/
Related
I used swig to generate a python module that is wrapping up some C++ code:
my .i file :
%module module_test
%{
#define SWIG_FILE_WITH_INIT
#include "headers.h"
%}
%include "headers.h"
I ran these commands :
swig -c++ -python swig.i
swig -Wall -c++ -python -external-runtime runtime_swig.h
After building, this generated a module_test.py and a _module_test.pyd files.
The wrapper works fine in python.
Now, from another C++ project I'm trying to load this new python module, using the following code:
Py_Initialize();
PySys_SetPath(L"path_to_my_files");
PyObject * pName = PyString_FromString("module_test.py");
PyObject *module = PyImport_Import(pName);
if(module == NULL)
{
PyErr_Print();
std::cout << "module == NULL !!";
exit(-1);
}
However the import fails with the error :
import imp
ImportError: No module named 'imp'
Can someone please tell me what's going on ? The module_test.py file generated by swig is doing an "import imp" in the code, but this import never failed when I run the file from python...
Do I need to specify something else so that the C++ code knows what "imp" is ?
thanks!
Solved it by using instead :
PyObject *sys = PyImport_ImportModule("sys");
PyObject *path = PyObject_GetAttrString(sys, "path");
PyList_Append(path, PyString_FromString("path_to_file"));
I'm using OpenCV 2.4.9 and g++. I've also tried with python 2.7.8 and python 3.4.1.
Here's a simple example:
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, char *argv[]) {
VideoCapture stream;
if (argc > 1) {
stream.open(argv[1]);
} else {
stream.open(0);
}
if (!stream.isOpened()) {
cout << "cannot open file";
}
while (true) {
Mat frame;
stream.read(frame);
imshow("preview", frame);
if (waitKey(30) >= 0)
break;
}
return 0;
}
This is compiled with:
g++ `pkg-config --libs opencv` -o test test.cpp
Works just fine with the camera, but not when reading from a file the program just hangs. Same is true with python. Any ideas?
Finally got around to fixing this. On Fedora 21 the opencv from the repository is built without ffmpeg support, because many codecs are not FOSS. Compiling from source did the trick.
I am porting a project from C++ Embarcadero XE6 32 bit to XE6 64 bit. We use embedded python libraries (and also some Python modules written in C).
I was able to get it to compile, but I can not link because there aren't any libs in the Python directory that the compiler bcc64 (a clang based compiler) can use.
Here's my code, it's just the simple "Here's how to embed python" example from the documentation really. We use Python 3.1; we could upgrade but I don't see the libs in newer versions either.
#define HAVE_ROUND
#define HAVE_ACOSH
#define HAVE_ASINH
#define HAVE_ATANH
#include <Python.h>
#pragma hdrstop
#pragma argsused
#ifdef _WIN32
#include <tchar.h>
#else
typedef char _TCHAR;
#define _tmain main
#endif
#include <stdio.h>
int _tmain(int argc, _TCHAR* argv[])
{
// Invoke the python intepreter
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print('Today is', ctime(time()))\n");
Py_Finalize();
system("Pause");
return 0;
}
mkexp libpython31.a C:\Windows\System32\python31.dll
Thanks to Ignacio for the help.
I am trying to build a C DLL which can be loaded within python using ctypes.windll.loadlibrary(...)
I can create a DLL and a client program all in C which work following the MinGW tutorial at http://www.mingw.org/wiki/MSVC_and_MinGW_DLLs.
When I try to load the same DLL within python I get an error:
OSError: [WinErrror 193] %1 is not a valid Win32 application
Can someone give me some idea as to what I am doing incorrectly?
Here are the files:
noise_dll.h
#ifndef NOISE_DLL_H
#define NOISE_DLL_H
// declspec will identify which functions are to be exported when
// building the dll and imported when 'including' this header for a client
#ifdef BUILDING_NOISE_DLL
#define NOISE_DLL __declspec(dllexport)
#else
#define NOISE_DLL __declspec(dllimport)
#endif
//this is a test function to see if the dll is working
// __stdcall => use ctypes.windll ...
int __stdcall NOISE_DLL hello(const char *s);
#endif // NOISE_DLL_H
noise_dll.c
#include <stdio.h>
#include "noise_dll.h"
__stdcall int hello(const char *s)
{
printf("Hello %s\n", s);
return 0;
}
I build the DLL with:
gcc -c -D BUILDING_NOISE_DLL noise_dll.c
gcc -shared -o noise_dll.dll noise_dll.o -Wl,--out-implib,libnoise_dll.a
The python code is simply:
import ctypes
my_dll = ctypes.windll.LoadLibrary("noise_dll")
and I get the error above: '%1 is not not a valid Win32 application'
I know the DLL is not completely wrong, because if i create a client file:
noise_client.c
#include <stdio.h>
#include "noise_dll.h"
int main(void)
{
hello("DLL");
return 0;
}
and build with:
gcc -c noise_client.c
gcc -o noise_client.exe noise_client.o -L. -lnoise_dll
I get a working executable. I have some understanding of all of what goes on in the code, options and preprocessor directives above, but am still a little fuzzy on how the .dll file and the .a file are used. I know if I remove the .a file I can still build the client, so I am not even sure what its purpose is. All I know is that it is some kind of archive format for multiple object files
I can ctypes.windll.loadlibrary(...) an ordinary windows DLL found in the windows/system32 without an issue.
One final point:
I am using 64 bit python 3.3. I am using the version of minGW tat comes with the recommended installer (mingw-get-inst-20120426.exe). I am not sure if it is 32 bit, or if that matters.
Thanks!
Use 32-bit python - your DLL probably wasn't compiled as 64 bit code.
When I try to embed python wx in C like this:
#include "stdafx.h"
#ifdef _DEBUG
#undef _DEBUG
#include <Python.h>
#define _DEBUG
#else
#include <Python.h>
#endif
int _tmain(int argc, _TCHAR* argv[])
{
PyObject* pyModule;
Py_Initialize();
//_pyModule = PyImport_ImportModule("__main__");
//_pyModule = PyImport_ImportModule("csi");
pyModule = PyImport_ImportModule("wx");
if(!pyModule)
PyErr_Print();
return 0;
}
it fails:
->Traceback (most recent call last):
File "C:\Python27\lib\site-packages\wx-2.8-msw-ansi\wx\__init__.py", line 45, in <module>
from wx._core import *
File "C:\Python27\lib\site-packages\wx-2.8-msw-ansi\wx\_core.py", line 4, in <module>
import _core_
ImportError: DLL load failed: The specified module could not be found.
could be a problem with msvc*90.dll files?
I am using VS2005, Python 2.7, wxPython 2.8.12.1 (ansi) for Python 2.7
Further MS VC++ 2008/2010 Redistributables are installed.
thanks for help.
Finally I found the solution:
it is a Manifest problem. Thanks to Microsof dll-hell...
This helps:
//_core_.pyd ImportError
// _core_.pyd is in fact a dll. it can be renamed.
// The problem is that _core_.pyd depends on some Microsoft.VC90.CRT libraries
//this dependency must be added to make it work
#pragma comment(linker, "\"/manifestdependency:type='win32' name='Microsoft.VC90.CRT' version='9.0.21022.8' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' language='*'\"")