调整了 Zaw Lin 的解决方案
- Ubuntu 18.04
- 通过安装OpenCV 3.2
apt install libopencv-dev
主要区别在于结果(
fg/
bg)图像是在python中创建/分配的,然后传递给c ++库。Zaw Lin的解决方案给我错误(errno
139-SIG_SEGV),因为该应用程序正在访问无效的内存区域。希望它可以节省一个人几个小时:)
mog2.cpp:
#include <opencv2/opencv.hpp>cv::BackgroundSubtractorMOG2 *mog = cv::createBackgroundSubtractorMOG2 (500, 16, false);extern "C" void getfg(int rows, int cols, unsigned char* imgData, unsigned char *fgD) { cv::Mat img(rows, cols, CV_8UC3, (void *) imgData); cv::Mat fg(rows, cols, CV_8UC1, fgD); mog->apply(img, fg);}extern "C" void getbg(int rows, int cols, unsigned char *bgD) { cv::Mat bg = cv::Mat(rows, cols, CV_8UC3, bgD); mog->getBackgroundImage(bg);}
像这样编译:
gcc -shared -o libmog2.so -fPIC ./mog2.cpp -lopencv_core -lopencv_highgui -lopencv_objdetect -lopencv_imgproc -lopencv_features2d -lopencv_ml -lopencv_calib3d -lopencv_video
然后是python:
mog2.py
import numpy as npimport ctypes as Cimport cv2libmog = C.cdll.LoadLibrary('path/to/libmog2.so')def getfg(img): (rows, cols) = (img.shape[0], img.shape[1]) res = np.zeros(dtype=np.uint8, shape=(rows, cols)) libmog.getfg(img.shape[0], img.shape[1], img.ctypes.data_as(C.POINTER(C.c_ubyte)), res.ctypes.data_as(C.POINTER(C.c_ubyte))) return resdef getbg(img): (rows, cols) = (img.shape[0], img.shape[1]) res = np.zeros(dtype=np.uint8, shape=(rows, cols, 3)) libmog.getbg(rows, cols, res.ctypes.data_as(C.POINTER(C.c_ubyte))) return resif __name__ == '__main__': c = cv2.VideoCapture(0) while 1: _, f = c.read() cv2.imshow('f', f) cv2.imshow('fg', getfg(f)) cv2.imshow('bg', getbg(f)) if cv2.waitKey(1) == 27: exit(0)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)