zoukankan      html  css  js  c++  java
  • python调用C++

    下面说的这种方法不是通过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)
  • 相关阅读:
    “TensorFlow 开发者出道计划”全攻略,玩转社区看这里!
    项目章程
    Android 开发环境的搭建(新环境)
    java中八种基本数据类型以及它们的封装类,String类型的一些理解
    一品黄山 天高云淡
    一品黄山 天高云淡
    黄山的日出日落
    宏村,寻找你的前世今生
    宏村,寻找你的前世今生
    git把本地文件上传到github上的步骤
  • 原文地址:https://www.cnblogs.com/zf-blog/p/11906786.html
Copyright © 2011-2022 走看看