python - 将 OpenCv Mat 从 C++ 传递到 Python
问题描述
我需要将 OpenCv 图像从 C++ 发送到 Python 以对其进行一些处理。Mat 将通过代码接收,但为简单起见,我在这里使用 imread 来回答问题。
我在代码的 C++ 部分所做的是:
#include <Python.h>
#include <arrayobject.h>
#include <iostream>
#include <opencv2/opencv.hpp>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
using namespace cv;
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Mat image = imread("test.jpg");
Py_Initialize();
PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue;
pName = PyUnicode_FromString("prog");
if (pName == NULL)
{
PyErr_Print();
return 0;
}
pModule = PyImport_Import(pName);
if (pModule == NULL)
{
PyErr_Print();
return 0;
}
pDict = PyModule_GetDict(pModule);
pFunc = PyDict_GetItemString(pDict, "add");
if (pFunc == NULL)
{
PyErr_Print();
return 0;
}
pArgs = PyTuple_New(1);
import_array ();
npy_intp dimensions[3] = {image.rows, image.cols, image.channels()};
pValue = PyArray_SimpleNewFromData(image.dims + 1, (npy_intp*)&dimensions, NPY_UINT8, image.data);
PyTuple_SetItem(pArgs, 0, pValue);
PyObject* pResult = PyObject_CallObject(pFunc, pArgs);
if(pResult == NULL)
cout<<"Calling the add method failed"<<endl;
long result = PyLong_AsLong(pResult);
cout<<"Result = "<<result<<endl;
Py_Finalize();
return 0;
}
此代码编译并运行。
对于 Python 部分:
import cv2
import numpy as np
def add (a):
print ("Contents of a :")
print (a)
# mat_array = cv2.fromarray(a, numpy.float32)
vis0 = cv.fromarray(a)
return 0
Python 代码从 C++ 接收 numpy 数组(我认为),当我打印 的内容时a
,我有一个输出(所以我认为我从 C++ 接收图像)。
现在我需要将数据转换为a
Python 中的 cv2 Mat 以便我可以处理它。
一旦我到达该mat_array = cv2.fromarray(a, numpy.float32)
行或vis0 = cv.fromarray(a)
代码崩溃并显示以下输出:
Exception ignored in: <module 'threading' from '/usr/lib/python3.5/threading.py'>
Traceback (most recent call last):
File "/usr/lib/python3.5/threading.py", line 1283, in _shutdown
assert tlock.locked()
SystemError: <built-in method locked of _thread.lock object at 0x7ff0f34d20d0> returned a result with an error set
如何正确发送/接收 Mat 对象?
解决方案
推荐阅读
- php - 在购物车中添加商品数量
- python - 如何使用 Python 中的键盘模块一次处理多个键?
- python - 健康方式禁用/删除子类中的方法
- reactjs - 无法加载资源:net::ERR_CONNECTION_REFUSED?Heroku,Axios
- java - 将 yaml 文件中的值检索到外部库中的字段
- arrays - 将命令行语句分配给 Perl 数组时的困惑
- discord - \n 换行符不保留代码块文本样式
- swift - WebFilter 阻止来自 Firebase 的动态链接
- angular - 类型“未知”不可分配给类型“键盘事件”.ts (2345)
- javascript - After Effects Slider 表达式以增加或减少可见层