有时要进行算法部署的加速,要把一些算法模块写成C/C++,如何混合编程,用python去调用C/C++呢?
首先把算法用C/C++写好,然后打包算法的动态链接库,具体方法参考:如何打包动态链接库
需要注意:如果是C++,在代码前后加上extern "C" {C++代码函数}。 //需要调用的C++程序就把声明写到这个extern "C"范围中
如果是ubuntu下,生成动态链接库so
之后开始python封装C/C++。
话不多说,上例子:
import ctypes
import cv2
import numpy as np
import time
from ctypes import *
## int ImgCheck(int height, int width, uchar* img_data);
## input: 图像高 图像宽 图像信息
## output: int类型
def Check_C(img_data):
ll = ctypes.cdll.LoadLibrary
lib = ll("./libImgCheck.so")
lib.ImageCheck.restype = ctypes.c_int
frame_data = img_data.ctypes.data_as(ctypes.POINTER(ctypes.c_ubyte))
R = lib.ImgCheck(img_data.shape[0], img_data.shape[1], frame_data)
return R
if __name__ == '__main__':
frame = cv2.imread('time.jpg')
start_time = time.time()
Result = Check_C(frame)
print("Result: ", Result)
elapse_time = time.time() - start_time
print("cost time (s):", elapse_time)
对于多张图片路径输入,可以这样python封装:
import ctypes
import cv2
import numpy as np
import time
from ctypes import *
## int ImgCompare(char* img_1, char* img_2)
## ./Test 1.jpg 2.jpg
def image_compare(image_path_1, image_path_2):
image_paths = [image_path_1, image_path_2]
ll = ctypes.cdll.LoadLibrary
lib = ll("./libImgCompare.so")
lib_ImageCompare = lib.ImgCompare
lib_ImageCompare.argtypes = [c_char_p() , c_char_p()]
lib_ImageCompare.restype = c_int
r_flag = lib_ImageCompare(image_paths[0].encode('utf-8'), image_paths[1].encode('utf-8'))
return r_flag
if __name__ == '__main__':
img_path_1 = '1.jpg'
img_path_2 = '2.jpg'
start_time = time.time()
Result = image_compare(img_path_1, img_path_2)
print("Result: ", Result)
elapse_time = time.time() - start_time
print("cost time (s):", elapse_time)