ctypes 传递opencv二值化图像给C++函数

这篇博客介绍了如何通过ctypes库将Python中OpenCV处理后的二值化图像传递给C++函数进行进一步处理。作者首先展示了C++函数的定义,用于接收和处理二维数组,然后在Python端读取图像,进行二值化、膨胀等操作,并将处理后的图像数据以无符号字符数组的形式传递给C++函数。最后,C++函数将处理结果写入文本文件,整个过程的时间复杂度也被记录下来。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ctypes 传递opencv二值化图像给C++函数

C++文件,因为python-opencv的二值化图像其实是存在连续的一个二维numpy数组中的,且取值为0-255,因此这里是unsigned char*,还有一点要注意,若要打印出matrix[i*columns + j],需要cout<<(int)matrix[i*columns + j];这么写

// 编译命令 g++ -o libtryPython.so -shared -fPIC tryPython.cpp
#include<iostream>
#include<fstream>
using namespace std;
extern "C"{
void show_matrix( unsigned char* matrix, int rows, int columns)
{
    ofstream outfile;
    outfile.open("output.txt");
    int i, j;
    for (i=0; i<rows; i++) {
        for (j=0; j<columns; j++) {
            if(matrix[i*columns + j]==255){
                outfile<<1;
            }
            else outfile<<(int)matrix[i*columns + j];
        }
        outfile<<endl;
    }
}
}

import cv2
import numpy as np
import ctypes
import time



lower = np.array([19,83,116])
upper = np.array([65,165,245])
COL=160
ROW=120

def imgProcess():
    '''
    description: 处理图片得到二值化图片
    param {*}
    return {*}
    '''    
    global img
    oriImg = cv2.imread("0.jpg")
    img_hsv = cv2.cvtColor(oriImg,cv2.COLOR_BGR2HSV)
    mask = cv2.inRange(img_hsv,lower,upper)
    img_resize = cv2.resize(mask,(COL,ROW),interpolation=cv2.INTER_NEAREST)
    element = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
    imgdilate = cv2.dilate(img_resize, element)  # 膨胀
    img = cv2.morphologyEx(imgdilate, cv2.MORPH_CLOSE, element)  # 先腐蚀后膨胀操作,原为腐蚀操作
    print(img.dtype)

def sendToC():
    lib = ctypes.cdll.LoadLibrary("./test.so")
    rows, cols = img.shape
    print(rows,cols)
    start = time.time()
    uint8_type = np.ctypeslib.ndpointer(ctypes.c_ubyte)
    lib.show_matrix.argtypes = [uint8_type,ctypes.c_int,ctypes.c_int]
    lib.show_matrix(img, rows, cols)
    print(time.time()-start)

imgProcess()
sendToC()




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值