I need to get the background model of a Mixture of Gaussian with opencv. I know that there is a method called getBackgroundImage in C++ I searched if it is possible to get i
here's a simple wrapper using ctypes, i have only tested on windows
cpp, build as dll
#include "opencv2/opencv.hpp"
cv::BackgroundSubtractorMOG2 mog(100, 16, false);
cv::Mat bg;
cv::Mat fg;
extern "C" __declspec(dllexport) unsigned char* getfg(int rows,int cols, unsigned char* fdata)
{
cv::Mat frame= cv::Mat(rows, cols, CV_8UC3,fdata);
mog(frame,fg);
//check fg.iscont(), copy as needed
return fg.data;
}
extern "C" __declspec(dllexport) unsigned char* getbg()
{
mog.getBackgroundImage(bg);
return bg.data;
}
python
import cv2
import numpy as np
import ctypes as C
lib = C.cdll.LoadLibrary('wrapper.dll')
def getfg(img):
ptr = lib.getfg(img.shape[0],img.shape[1],img.ctypes.data_as(C.POINTER(C.c_ubyte)))
buf = (C.c_ubyte * img.shape[0] * img.shape[1] * 1).from_address(ptr)
res = np.ndarray(buffer=buf, dtype=np.uint8,
shape=(img.shape[0], img.shape[1], 1))
return res
def getbg(img):
ptr = lib.getbg()
buf = (C.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))
return res
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)