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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM