Cython使用,python提供c++接口

来源:互联网 发布:用python做数据分析 编辑:程序博客网 时间:2024/06/05 07:16

一般大家用c++为python提供接口的比较多,python为c++提供接口的方法介绍不多,感觉用起来也蛮方便。有些方法在python下有很好的封装,可以调用也是不错的。
看了http://docs.cython.org/src/tutorial/cython_tutorial.html ,发现按照教程可以生成.so 文件。然后就试了一下,果然c++可以调用。
不是太会写教程,就记录一下操作的流程吧,希望对大家有帮助。

首先写一个python文件,命名为libtest_cython.pyx

#!/usr/bin/env python2#coding:utf-8import numpy as npimport cv2cdef public char* test(unsigned char* in_img,int rows,int cols):        img = np.empty([rows,cols,3],dtype=np.uint8)    for i in range(rows):        for j in range(cols):            for m in range(3):                img[i][j][m] = int(in_img[i*cols*3+j*3+m])    cv2.imwrite('../tmp.jpg',img)    return "Hello World!"

然后按照官方教程编写setup.py文件

from distutils.core import setupfrom Cython.Build import cythonizesetup(    ext_modules = cythonize("libtest_cython.pyx"))

接着写一个sh脚本,cython.sh

#!/usr/bin/env bashpython setup.py build_ext --inplace

下面是c++文件test.cpp,用来调用python生成的动态库
基本的功能是通过指针将图片传入到python生成的.so中,保存图片,然后传回Hello World! 的字符串并打印。

#include <iostream>#include <Python.h>#include "libtest_cython.h"#include <opencv2/opencv.hpp>#include <opencv2/core/core.hpp>#include <iostream>using namespace std;using namespace cv;int main(){      Py_Initialize();   //初始化python    initlibtest_cython();  //初始化.so    Mat src;    src = imread("../1.jpg");    unsigned char* f = src.data;    cout<<test(f,src.rows,src.cols)<<endl;    Py_Finalize();   //结束python使用    return 0;  }  

然后编写CMakeLists.txt,这里可能需要根据自己的python 安装位置对cmake进行修改

project(test_cython)                           cmake_minimum_required(VERSION 2.8)    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")    set(source test.cpp)   include_directories(/usr/include/python2.7/)    #Python.h     link_directories(/usr/lib/x86_64-linux-gnu/)    #python2.7.solink_directories(${CMAKE_SOURCE_DIR})      #test_cython.sofind_package(OpenCV REQUIRED)   add_executable(test_cython ${source})target_link_libraries(test_cython python2.7.so test_cython.so ${OpenCV_LIBS})

最后是run.sh 脚本

#! /usr/bin/env bashcd ./buildcmake .. make -j8./test_cython

接着只要运行下面脚本就可以看到效果。

sh cython.shsh run.sh 

第一步是通过shell脚本运行了setup.py 生成了.so 文件以及.h 文件
第二步先是通过Cmake生成了Makefile,然后编译可执行文件,再运行。
运行的结果为,将文件夹下的1.jpg文件复制到tmp.jpg ,以及打印Hello World!

0 0
原创粉丝点击