我有一个使用 OpenCV 库用 Python 编写的图像处理函数 (IMP)。
现在我想从 C 代码调用 IMP:
#include "/usr/include/python2.7/Python.h"
int main()
{
PyObject *pName, *pModule, *pDict, *pFun, *pValue, main_module;
// Initialize the Python Interpreter
Py_Initialize();
// Build the name object
pName = PyString_FromString("test");
if(pName)printf("OK\n");
// Load the module object
pModule = PyImport_Import(pName);
// pFunc is also a borrowed reference
pFun = PyObject_GetAttrString(pModule, "IMP");
if (PyCallable_Check(pFun))
{
//PyObject_CallObject(pFun, NULL);
PyObject_CallFunction(pFun,"o",framebuffer);
}
else
{
PyErr_Print();
}
// Clean up
Py_DECREF(pModule);
Py_DECREF(pName);
Py_DECREF(pFun);
// Finish the Python Interpreter
Py_Finalize();
getchar();
return 0;
}
如何准备“framebuffer”传递到我的 IMP python 函数中?
有人可以帮我展示一个打包在 CV2 可以理解的对象中的示例图像,并使用上面的示例 C 代码将其传递给 IMP 吗?非常感谢您的帮助。
最佳答案
我想我找到了我需要的:只需在我的 test.py 中创建一个模板“framebuffer”:
import numpy as np
import cv2
framebuffer = cv2.imread('pic.jpg',cv2.IMREAD_COLOR)
def IMP(p):
print "I am here!"
print "image.shape h,w,d=",p.shape
cv2.imshow("picture",p)
cv2.waitKey(0)
cv2.destroyAllWindows()
然后在我的 test.c 中,我从 pDict 中 grep“帧缓冲区”以进行进一步操作,然后调用 IMP:
#include "/usr/include/python2.7/Python.h"
#include <numpy/arrayobject.h>
int main()
{
PyObject *pName, *pModule, *pDict, *pFun, *pValue, *pArgs, *pFB;
int i,j;
// Initialize the Python Interpreter
Py_Initialize();
// Build the name object
pName = PyString_FromString("test");
if(pName)printf("OK\n");
// Load the module object
pModule = PyImport_Import(pName);
// pDict is a borrowed reference
pDict = PyModule_GetDict(pModule);
// pFunc is also a borrowed reference
pFun = PyDict_GetItemString(pDict, "IMP");
pFB = PyDict_GetItemString(pDict, "framebuffer");
if (pFB != NULL)
printf("got the framebuffer as pFB!\n");
//copy a new framebuffer into pFB here!!!
uint8_t *ptr;
ptr = PyArray_DATA(pFB);
int col,row,color;
int NCOL = 0, NROW = 0, NCLR = 0;
int ndim=0;
ndim = PyArray_NDIM(pFB);
NROW = PyArray_DIM(pFB,0);
NCOL = PyArray_DIM(pFB,1);
NCLR = PyArray_DIM(pFB,2);
for (row=0;row<NROW;row++)
for (col=0;col<NCOL;col++)
for (color=0;color<NCLR;color++)
{
*ptr = pixel_value; //copy your framebuffer pixel value to pFB!!!
ptr++;
}
pArgs = PyTuple_New(1);
PyTuple_SetItem(pArgs,0,pFB);
if (PyCallable_Check(pFun))
{
PyObject_CallObject(pFun, pArgs); //call python IMP with updated framebuffer!!!
}
else
{
PyErr_Print();
}
// Clean up
Py_DECREF(pModule);
Py_DECREF(pName);
//Py_DECREF(pDict); //do not decref on pDict because it is borrowed ref, otherwise it will crash Py_Finalize()!!!
//Py_DECREF(pArgs);
//Py_DECREF(pFun);
//Py_DECREF(pFB);
// Finish the Python Interpreter
Py_Finalize();
return 0;
}
就是这样!
关于python - 如何使用 OpenCV 将帧缓冲区从 C 传递到 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27110902/