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()
|