简体   繁体   中英

Python OpenCV pass mat ptr to c++ code

Using Python 3 and OpenCV 3.

I have written some DLL's in C++ that export a few C-type functions and a uchar3 c-type struct. 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. I am pretty new to Python, but I see that ctypes provides a fairly straightforward way to use DLL's.

What I can't sort out is how to get a pointer to the OpenCV Mat from within Python. Using C++, I do the following:

    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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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