我用python打开图片,发送给C函数处理,返回图片如何正确从c函数中获取图片?
分段错误
程式码范例:
C++
// t_lib.cpp
#include "opencv2/opencv.hpp"
extern "C" unsigned char* getfg(int rows,int cols, unsigned char* fdata)
//extern "C" void getfg(int rows,int cols, unsigned char* fdata)
{
cv::Mat frame = cv::Mat(rows, cols, CV_8UC3, (void *) fdata);
// Work
//cv::imshow("Display window C++", frame);
//cv::waitKey(0);
// do something
return frame.data; //fdata;
}
Python 2.7语言
# test.py
import cv2
import numpy as np
import ctypes
lib = ctypes.cdll.LoadLibrary('./lib.so')
def getfg(img):
ptr = lib.getfg(img.shape[0], img.shape[1], img.ctypes.data_as(ctypes.POINTER(ctypes.c_ubyte)))
buf = (ctypes.c_ubyte * img.shape[0] * img.shape[1] * 3).from_address(ptr)
res = np.ndarray(buffer=buf, dtype=np.uint8, shape=(img.shape[0], img.shape[1], 3), order="C")
return res
f = cv2.imread("sample.jpg")
#gray_image = cv2.cvtColor(f, cv2.COLOR_BGR2GRAY)
AS = getfg(f)
print AS.shape
#np.array(AS)[0]
cv2.imshow("Window Python", AS)
cv2.waitKey(0)
编译:
g++ -c -fPIC t_lib.cpp -o lib -lX11 $(pkg-config opencv --cflags --libs) -I/usr/include/python2.7 -I/usr/lib/python2.7;
g++ -shared -Wl,-soname,lib.so -o lib.so lib -lopencv_core -lopencv_highgui -lopencv_imgproc
用于查看opencv库命令:
pkg-config opencv --cflags --libs
输出:
-I/usr/include/opencv -lopencv_shape -lopencv_stitching
-lopencv_superres -lopencv_videostab -lopencv_aruco
-lopencv_bgsegm -lopencv_bioinspired -lopencv_ccalib
-lopencv_datasets -lopencv_dpm -lopencv_face
-lopencv_freetype -lopencv_fuzzy -lopencv_hdf
-lopencv_line_descriptor -lopencv_optflow -lopencv_video
-lopencv_plot -lopencv_reg -lopencv_saliency -lopencv_stereo
-lopencv_structured_light -lopencv_phase_unwrapping -lopencv_rgbd
-lopencv_viz -lopencv_surface_matching -lopencv_text
-lopencv_ximgproc -lopencv_calib3d -lopencv_features2d
-lopencv_flann -lopencv_xobjdetect -lopencv_objdetect
-lopencv_ml -lopencv_xphoto -lopencv_highgui
-lopencv_videoio -lopencv_imgcodecs -lopencv_photo
-lopencv_imgproc -lopencv_core
版本c++ OpenCV 3.2.0
2条答案
按热度按时间xwmevbvl1#
你必须根据this把这个c++代码编译成一个共享库,然后写一个 Package 器
luaexgnf2#
其中一种方法是使用memcpy
python3.x``python3.x
c++
cpp_function.cpp
使用
g++ -shared -fPIC cpp_function.cpp -o cpp_function.so -I /usr/include/opencv4/ -L /usr/lib -lopencv_core -lopencv_imgproc
编译