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)
  • 相关阅读:
    Oracle数据库导入(数据泵导)
    C# 根据WCF 的url动态调用WCF
    winform嵌套浏览器
    微信支付服务商模式 配置
    结对项目-增强型科学计算器
    vscode编辑远程linux系统下c/c++代码实现代码补全
    Linux development with C++ in Visual Studio
    用VS2015开发Linux程序详细教程-配置篇
    Go语言环境搭建详解(2020版)
    bat脚本实现后台运行cmd命令
  • 原文地址:https://www.cnblogs.com/zf-blog/p/11906786.html
Copyright © 2011-2022 走看看