c++封装类的动态库、python调用
c++封装类的动态库
3.1.1 demo.h文件
#ifndef _DEMOSO_H
#define _DEMOSO_H
// OpenCV includes
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc.hpp>
struct struHeadPose
{
float angleX;
float angleY;
float angleZ;
};
class CCaculateFaceAngle
{
public:
int getPose(int* imgData, int h, int w, int channels, float cx, float cy, float fx, float fy,struHeadPose& pose);
int LoadModel(char* sModelPath);
private:
LandmarkDetector::FaceModelParameters m_det_parameters;
LandmarkDetector::CLNF m_clnf_model;
};
#endif // _DEMOSO_H
3.1.2 demo.cpp文件
#include "demo.h"
int CCaculateFaceAngle::getPose(int* imgData, int h, int w, int channels, float cx, float cy, float fx, float fy, struHeadPose& pose)
{
内容省略
}
int CCaculateFaceAngle::LoadModel(char* sModelPath)
{
内容省略
}
//以下是重点,不然不会导出c++的类。
extern "C"
{
CCaculateFaceAngle obj;
int getPose(int* imgData, int h, int w, int channels, float cx, float cy, float fx, float fy,struHeadPose& pose)
{
return obj.getPose(imgData, h, w, channels, cx, cy, fx, fy,pose);
}
int LoadModel(char* sModelPath)
{
return obj.LoadModel(sModelPath);
}
}
3.2 python调用c++类
from ctypes import *
import cv2
import ctypes
import numpy as np
dll = cdll.LoadLibrary('/LandmarkDetector/class_so/demo.so');
# model path
sModelPath = "/LandmarkDetector/model/main_clnf_general.txt"
#image data
src = cv2.imread("/OpenFace-master/test/face_0.jpg") #0-gray
cols = src.shape[1]
rows = src.shape[0]
#print('img shape:{}'.format(src.shape))
channels = 0
if 3==len(src.shape):
channels = 3
src = np.asarray(src, dtype=np.int)
src1 = src.ctypes.data_as(ctypes.c_char_p)
#fx fy cx cy
cx = cols / 2.0
cy = rows / 2.0
fx = 500 * (cols / 640.0)
fy = 500 * (rows / 480.0)
fx = (fx + fy) / 2.0
fy = fx
cx1 = c_float(cx)
cy1 = c_float(cy)
fx1 = c_float(fx)
fy1 = c_float(fy)
#head pose
class struHeadPose(ctypes.Structure):
_fields_ = [("angleX", ctypes.c_float),("angleY", ctypes.c_float),("angleZ", ctypes.c_float)]
pose = struHeadPose(0.0, 0.0, 0.0)
if dll.LoadModel(sModelPath) > -1:
t = dll.getPose(src1, rows, cols, channels, cx1, cy1, fx1, fy1, ctypes.byref(pose))
print (pose.angleX)
print (pose.angleY)
print (pose.angleZ)