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"

// python 传递数组到 c++ 端时, 需要将其拉平为 1 维.
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())

 

  • 5
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值