Python OpenCV将mat ptr传递给c++;代码
使用Python 3和OpenCV 3Python OpenCV将mat ptr传递给c++;代码,python,c++,opencv,dll,ctypes,Python,C++,Opencv,Dll,Ctypes,使用Python 3和OpenCV 3 我在C++中写了一些DLL,导出了一些C类型函数和一个UCAR3 C型结构。我一直在使用OpenCV中的这些项目在C++项目中,但是我也想能够从Python访问它们。我对Python非常陌生,但我看到ctypes提供了一种相当简单的使用DLL的方法 我无法解决的是如何从Python中获取指向OpenCV Mat的指针。使用C++,我做以下操作:< /P> myMatDataPointer = myMat.ptr<uchar>(0) m
我在C++中写了一些DLL,导出了一些C类型函数和一个UCAR3 C型结构。我一直在使用OpenCV中的这些项目在C++项目中,但是我也想能够从Python访问它们。我对Python非常陌生,但我看到ctypes提供了一种相当简单的使用DLL的方法
我无法解决的是如何从Python中获取指向OpenCV Mat的指针。使用C++,我做以下操作:< /P> myMatDataPointer = myMat.ptr<uchar>(0)
myMatDataPointer=myMat.ptr(0)
理想情况下,我希望找到一种简单的方法来使用uchar3结构,但我发现ctypes支持开箱即用的char*,因此如果我能找到一个指向Mat数据的方法,我就可以将就一下了。我刚刚意识到这一点从未得到回答。我现在可以提供一个我一直在使用的。它支持使用纯C接口进行双向通信
import cv2
import ctypes
import numpy as np
import numpy.ctypeslib as npct
# Tell numpy what kind of pointer we want to use, load the dll
ucharPtr = npct.ndpointer(dtype=np.uint8, ndim=1, flags='CONTIGUOUS')
dll = ctypes.WinDLL('file.dll')
# the 'process_frame' function exported by the dll reads from
# the first pointer and writes to the second
process = dll['process_frame']
process.restype = None
process.argtypes = [ucharPtr, ucharPtr]
# Make two empty images for demonstration purposes
# OpenCV Python uses numpy arrays images, not Mat's
# This makes it super easy to work with images in python
in_image = np.zeros(shape,np.uint8,order='C').ravel()
out_image = np.zeros(self.shape,np.uint8,order='C').ravel()
process(in_image, out_image)
当然,我本可以在in_图像中使用更有趣的东西,但是我们已经成功地将一个图像从OpenCV python发送到dll,并且可以使用我们的dll返回的任何东西。您必须为库创建一个纯C接口。对于C++,尝试需要编译器的框架,例如Cython、Sigg或BooSt.Python。是的,DLL的导出纯C函数(据我所知,不可能从DLL导出非PURE C函数)。问题是这些函数需要一个指向OpenCV mat数据的指针。我知道如何在C++中访问这个,但不在Python中访问。有C++的DLL(例如微软的ULI.DLL,控制台程序使用的实用程序库),但是由于没有跨平台的、稳定的ABI,所以一般来说不是好主意,这样的DLL不能很容易地与cType一起使用。在Windows上,C++DEVs创建COM DLL很常见,您可以使用COMYPE或PythOncom。对于获取指针,可以编写返回指针的C++存根函数。一般来说,这调用C++构造函数来获得Python代理类的<代码>这个实例。代理调用C++方法的C包装,手动提供