简体   繁体   English

Python OpenCV将Mat Ptr传递给C ++代码

[英]Python OpenCV pass mat ptr to c++ code

Using Python 3 and OpenCV 3. 使用Python 3和OpenCV 3。

I have written some DLL's in C++ that export a few C-type functions and a uchar3 c-type struct. 我用C ++编写了一些DLL,这些DLL导出了一些C型函数和uchar3 c型结构。 I have been using these with OpenCV in a C++ project, but I would like to be able to access them from Python as well. 我已经在C ++项目中将它们与OpenCV一起使用,但是我也希望能够从Python访问它们。 I am pretty new to Python, but I see that ctypes provides a fairly straightforward way to use DLL's. 我对Python相当陌生,但是我看到ctypes提供了一种使用DLL的相当简单的方法。

What I can't sort out is how to get a pointer to the OpenCV Mat from within Python. 我无法解决的是如何从Python中获取指向OpenCV Mat的指针。 Using C++, I do the following: 使用C ++,我执行以下操作:

    myMatDataPointer = myMat.ptr<uchar>(0)

Ideally, I would like to find an easy way to use the uchar3 struct, but I see that a char* is supported out-of-the-box by ctypes, so I can make do with that if I can figure out how to get one pointing to the Mat's data. 理想情况下,我想找到一种使用uchar3结构的简便方法,但是我发现ctypes支持开箱即用char *,因此,如果可以弄清楚如何获取它,就可以使用它。一个指向Mat的数据。

I just realized that this never was answered. 我只是意识到这从未得到回答。 I can now provide one that I've been using. 现在,我可以提供一个我一直在使用的。 It supports bi-directional communication using a pure C interface. 它支持使用纯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)

I could have used something more interesting for in_image of course, but we've successfully sent an image from OpenCV python to the dll, and can use whatever our dll gave back. 我本可以为in_image使用一些更有趣的东西,但是我们已经成功地将图像从OpenCV python发送到了dll,并且可以使用我们的dll所提供的任何东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM