下面说的这种方法不是通过swig,而是先将C++模块编译成动态链接库.so,再利用python模块ctypes进行调用;
1、编写C++程序
#include<opencv2/opencv.hpp>
#include<vector>
extern "C" //需要调用的C++程序就把声明写到这个extern "C"范围中;
{
float test(int height, int width, uchar* frame_data);
}
float test(int height, int width, uchar* frame_data)
{
cv::Mat image(height, width, CV_8UC3);
uchar* pxvec =image.ptr<uchar>(0);
int count = 0;
for (int row = 0; row < height; row++)
{
pxvec = image.ptr<uchar>(row);
for(int col = 0; col < width; col++)
{
for(int c = 0; c < 3; c++)
{
pxvec[col*3+c] = frame_data[count];
count++;
}
}
}
std::vector<int> a(3);
float value = 0.2;
return value;
}
2、编写CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project( test )
find_package( OpenCV REQUIRED )
add_library( test SHARED test.cpp ) //注意这里是add_library,表示生成对应的动态链接库,如果是add_extuable,则是生成对应的可执行文件
target_link_libraries( test ${OpenCV_LIBS} )
3、编译
cmake . make
经过编译后会得到对应的.so文件,然后再在python中调用
4、在python中使用ctypes进行调用
import ctypes
import cv2
import numpy as np
ll = ctypes.cdll.LoadLibrary
lib = ll("./libtest.so")
lib.test.restype = ctypes.c_float
frame = cv2.imread('1.jpg')
frame_data = np.asarray(frame, dtype=np.uint8)
frame_data = frame_data.ctypes.data_as(ctypes.c_char_p)
value = lib.test(frame.shape[0], frame.shape[1], frame_data)
print (value)