欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

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

发布时间:2023/12/14 40 豆豆
生活随笔 收集整理的这篇文章主要介绍了 ctypes 传递opencv二值化图像给C++函数 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

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 timelower = np.array([19,83,116]) upper = np.array([65,165,245]) COL=160 ROW=120def imgProcess():'''description: 处理图片得到二值化图片param {*}return {*}''' global imgoriImg = 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.shapeprint(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()

总结

以上是生活随笔为你收集整理的ctypes 传递opencv二值化图像给C++函数的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。