python 調用c++處理數組和圖片

基本流程:

  1. 定義cpp文件實現算法邏輯,因爲編譯器在編譯的時候是會把c++函數改名,所以對於python調用的函數是要聲明爲以c的方式編譯
    #include "execute.h"
    
    extern "C"
    {
    Execute execute;
    void show_matrix(int *matrix, int rows, int columns) {
        execute.show_matrix(matrix, rows, columns);
    }
    
    // 傳遞uchar數組到c++
    void show_uchar_matrix(uchar *matrix, int rows, int columns) {
        execute.show_uchar_matrix(matrix, rows, columns);
    }
    
    // 傳遞圖片到c++
    void transfer_image(uchar *frame_data, int height, int width, int channel) {
        execute.transfer_image(frame_data, height, width, channel);
    }
    
    // 在c++層處理數組 並返回值
    float sum_array(float *data, int len) {
        return execute.sum_array(data, len);
    }
    
    // 在c++層處理數組
    void change_array(float *data, int len) {
        execute.change_array(data, len);
    }
    
    // 傳遞結構體到 c++ 層 並返回結構體
    result transfer_struct(result t) {
        return execute.transfer_struct(t);
    }
    
    }
    

     

  2. 將cpp文件打包爲動態庫 so 文件

  3. 在python中加載 so 文件,調用對應的cpp算法

一個簡單的 c++ 例子

execute.h 頭文件

#ifndef PY_C_TEST_EXCUTE_H
#define PY_C_TEST_EXCUTE_H

#include <iostream>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core/core.hpp"

typedef struct Result {
    int a;
    char *b;
} result;

class Execute {
public:
    // 傳遞int數組到c++
    void show_matrix(int *matrix, int rows, int columns);

    // 傳遞uchar數組到c++
    void show_uchar_matrix(uchar *matrix, int rows, int columns);

    // 傳遞圖片到c++
    void transfer_image(uchar *frame_data, int height, int width, int channel);

    // 在c++層處理數組
    void change_array(float *data, int len);

    // 在c++層處理數組
    float sum_array(float *data, int len);

    // 傳遞結構體到c++層並傳回
    result transfer_struct(result t);
};


#endif //PY_C_TEST_EXCUTE_H
#include "execute.h"

void Execute::show_matrix(int *matrix, int rows, int columns) {
    int row, col;
    for (row = 0; row < rows; row++) {
        for (col = 0; col < columns; col++) {
            printf("matrix[%d][%d] = %d\n", row, col, matrix[row * columns + col]);
        }
    }
}

void Execute::show_uchar_matrix(uchar *matrix, int rows, int columns) {
    int row, col;
    for (row = 0; row < rows; row++) {
        for (col = 0; col < columns; col++) {
            printf("matrix[%d][%d] = %d\n", row, col, int(matrix[row * columns + col]));
        }
    }
}

void Execute::transfer_image(uchar *frame_data, int height, int width, int channel) {
    int type = CV_8UC1;
    if (channel == 3) {
        type = CV_8UC3;
    }
    cv::Mat image(height, width, type);
    for (int row = 0; row < height; row++) {
        uchar *pxvec = image.ptr<uchar>(row);
        for (int col = 0; col < width; col++) {
            for (int c = 0; c < channel; c++) {
                pxvec[col * channel + c] = frame_data[row * width * channel + channel * col + c];
            }
        }
    }
    cv::imshow("image", image);
    cv::waitKey(0);
}

float Execute::sum_array(float *data, int len) {
    float sum = 0;
    for (int i = 0; i < len; i++) {
        sum += data[i];
    }
    return sum;
}

void Execute::change_array(float *data, int len) {
    for (int i = 0; i < len; i++) {
        data[i] += len;
    }
}

result Execute::transfer_struct(result t) {
    t.a = t.a + t.a;
    printf("%s\n",t.b);
    t.b = "new string from c++";
    return t;
}

1. python 傳遞數組到 c++ 端

import ctypes
import cv2
import numpy as np

ll = ctypes.cdll.LoadLibrary
lib = ll("./libc_opencv.so")
arr = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]])
tmp = np.asarray(arr, dtype=np.uint8)
rows, cols = tmp.shape
dataptr = tmp.ctypes.data_as(ctypes.c_char_p)
lib.show_uchar_matrix(dataptr, rows, cols)

傳遞的numpy數組類型需要與c++端接收的數組類型相同, 具體對應關係可以查詢 python的ctypes文檔

2. python端傳遞圖片到 c++ 端

ll = ctypes.cdll.LoadLibrary
lib = ll("./libc_opencv.so")
tmp = cv2.imread("full_finish.jpg", cv2.IMREAD_GRAYSCALE)
rows, cols = tmp.shape
dataptr = tmp.ctypes.data_as(ctypes.c_char_p)
lib.transfer_image(dataptr, rows, cols, 1)

3. 傳遞數組到 c++ 端並返回值

ll = ctypes.cdll.LoadLibrary
lib = ll("./libc_opencv.so")
pyarray = [1., 2., 3., 4., 5.1]
carray = (ctypes.c_float * len(pyarray))(*pyarray)
# 定義返回值類型
lib.sum_array.restype = ctypes.c_float
sum = lib.sum_array(carray, len(pyarray))
print(sum)

默認python端讀到的是 c++ 返回值的地址,需要顯式地定義返回值類型

4. 傳遞數組到 c++ 端並返回數組

需要先在Python端將返回數組定義出來,一同傳入 c++ 端,在 c++ 端將數據寫入,再通過np.array將 c++ 數組轉回numpy數組類型

ll = ctypes.cdll.LoadLibrary
lib = ll("./libc_opencv.so")
pyarray = [1., 2., 3., 4., 5.1]
carray = (ctypes.c_float * len(pyarray))(*pyarray)
lib.change_array(carray, len(pyarray))
print(np.array(carray))

5. 傳遞結構體到 c++ 端並返回結構體

在c++端定義結構體

typedef struct Result {
    int a;
    char *b;
} result;

在python端定義相同的結構體

class Result(Structure):
    _fields_ = [('a', c_int),
                ('b', c_char_p)]

在python端調用

ll = ctypes.cdll.LoadLibrary
lib = ll("./libc_opencv.so")

# 賦予結構體的數據必須轉成 ctype 格式
a = ctypes.c_int(220)
b = ctypes.c_char_p('Hello'.encode())


t = Result()
t.a = a
t.b = b

# 定義返回類型爲結構體類型
lib.transfer_struct.restype = Result

t = lib.transfer_struct(t)
print(t.a)
print(t.b.decode())

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章