--- title: c++ call python function tags: c++, python description: c++ compress images into unsigned char and sending parameters to python function --- # c++ call python function python is writen by c++, so c++ and python should be able to call each function. The example use c++ to read image and call python function to save the image. Python.h is included in python normal installation. It provide interaction between c++ and python. ## Build necessary package ### Build opencv from source for c++ Opencv4 CMakeLists.txt -> OPENCV_GENERATE_PKGCONFIG option default is OFF, change to ON. **CMakeLists.txt** ``` ... OCV_OPTION(OPENCV_GENERATE_PKGCONFIG "Generate .pc file for pkg-config build tool (deprecated)" OFF) ... ``` Add Opencv4.4.0 PKG_CONFIG_PATH to system ``` $ export PKG_CONFIG_PATH=/opencv-4.4.0/build/unix-install:$PKG_CONFIG_PATH ``` ### Install opencv-python for python ``` $ pip3 install opencv-python ``` ## python scipt **inference.py** ``` import numpy as np import cv2 def arrayreset(image): b = image[:,:,0] g = image[:,:,1] r = image[:,:,2] b = np.expand_dims(b, axis=2) g = np.expand_dims(g, axis=2) r = np.expand_dims(r, axis=2) image = np.concatenate((b, g, r), axis=2) return image def load_image(image): img = arrayreset(image) cv2.imwrite("test.jpg",img) ``` ## c++ scipt **main.cpp** ``` #include <iostream> #include <Python.h> #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include </usr/local/lib/python3.6/dist-packages/numpy/core/include/numpy/arrayobject.h> int transport() { Py_Initialize(); import_array(); PyObject* sys = PyImport_ImportModule("numpy"); PyRun_SimpleString("import sys"); // 执行 python 中的短语句 PyRun_SimpleString("sys.path.append('./')"); PyObject *pModule(0); pModule = PyImport_ImportModule("inference");//myModel:Python文件名 cv::Mat img = cv::imread("2.jpg"); int m, n; n = img.cols*3; m = img.rows; unsigned char *data = (unsigned char*)malloc(sizeof(unsigned char) * m * n); int p = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { data[p] = img.at<unsigned char>(i, j); p++; } } npy_intp Dims[3] = {img.rows, img.cols, 3}; //给定维度信息 PyObject *PyArray = PyArray_SimpleNewFromData(3, Dims, NPY_UBYTE, data); PyObject *pDict = PyModule_GetDict(pModule); PyObject *ArgArray = PyTuple_New(1); PyTuple_SetItem(ArgArray, 0, PyArray); PyObject *pFuncFive = PyDict_GetItemString(pDict, "load_image"); PyObject_CallObject(pFuncFive, ArgArray); } int main() { transport(); system("pause"); return 0; } ``` Build main.cpp ``` $ g++ main.cpp -o main -I/usr/include/python3.6m/ -lpython3.6m `pkg-config --cflags --libs opencv4` ``` execute ./main to call python function ``` $ ./main ``` ## Reference * https://blog.csdn.net/qq_41623632/article/details/114600403 * https://blog.csdn.net/qq_38109843/article/details/87969732 ## Thank you! :dash: You can find me on - GitHub: https://github.com/shaung08 - Email: a2369875@gmail.com