How can I pass an OpenCV 3 image from Python 3 to C++? In technical terms, how do I convert a NumPy array to a cv::Mat object and back?
To make my question more specific, let's assume:
I have a Python program that uses OpenCV to capture images from the webcam and display them. (In real life, I'm prototyping further functions there, such as some web server features.)
cam.py:
import cv2 def main(): cam = cv2.VideoCapture(0) while True: _, img = cam.read() cv2.imshow('cam', img) # TODO: Call the C++ function from the sample below # img = helloWorld(img) cv2.waitKey(16) # let imshow do its work (16 ms -> 60 FPS) cv2.destroyAllWindows() if __name__ == '__main__': main()Run
python3 cam.pyto try it out.I would like to use an existing
helloWorldfunction from some C++ library that processes the OpenCV images. (In real life, it does some signal processing and extracts information from the images.) For the sake of simplicity, my sample function below just mirrors the image horizontally. Themainfunction is there to check thathelloWorldworks as expected.cam.cpp:
#include <opencv2/highgui/highgui.hpp> using namespace cv; using namespace std; void helloWorld(Mat img) { flip(img, img, 1); } int main() { VideoCapture stream1(0); while (true) { Mat img; stream1.read(img); helloWorld(img); imshow("cam", img); waitKey(16); } return 0; }To compile this code, run
g++ -std=c++11 -lopencv_core -lopencv_highgui -lopencv_videoio cam.cpp -o cam, then execute./camto try it out.
Now what changes should I make to my code so that I can call the helloWorld C++ function out of my Python app? Luckily, I have access to the C++ source code, so that I can extend and recompile it if necessary.