首页 \ 问答 \ 在python中从BackgroundSubtractorMOG2获取背景模型(Get background model from BackgroundSubtractorMOG2 in python)

在python中从BackgroundSubtractorMOG2获取背景模型(Get background model from BackgroundSubtractorMOG2 in python)

我需要使用opencv获得高斯混合的背景模型。 我知道在C ++中有一个名为getBackgroundImage的方法,我搜索了是否有可能在python界面中获取它,但我没有得到好的结果。 我试过opencv 3.0.0-dev,因为它有BackgroundSubtractorMOG2实现,但help()函数不记录背景模型的方法实现。 你知道是否有无证实施? 我搜索了如何编辑opencv源码来实现python实现,但是我还没有找到关于它的文档。 我更喜欢避免使用scipy.weave编译c ++代码,此外我不知道scipy.weave是否适用于这种情况


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 it in python interface but I haven't get good result. I Tried opencv 3.0.0-dev because it has BackgroundSubtractorMOG2 implementation, but help() function don't document method implementation for background model. Do you know if there is undocumented implementation? I searched how to edit opencv source to implement a python implementation but i haven't found documentation about it. I prefer avoid to use scipy.weave to compile c++ code, furthermore i don't know if scipy.weave is useful in thi situation


原文:https://stackoverflow.com/questions/19031836
更新时间:2019-07-12 07:09

最满意答案

Zaw Lin在Ubuntu 12.04中的解决方案:

主要区别在于结果( fg / bg )图像是在python中创建/分配的,然后传递给c ++ lib。 Zaw Lin的解决方案给我错误(errno 139 - SIG_SEGV),因为该应用程序正在访问无效的内存区域。 希望它可以节省几个小时:)

mog2.cpp:

#include <opencv2/opencv.hpp>

cv::BackgroundSubtractorMOG2 mog(100, 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(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_contrib -lopencv_video

然后python:

mog2.py

import numpy as np
import ctypes as C
import cv2

libmog = 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 res


def 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 res


if __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)

Zaw Lin's solution in Ubuntu 12.04:

The main difference is that the result (fg / bg) images are created/allocated in python and then passed down to the c++ lib. Zaw Lin's solution was giving me errors (errno 139 - SIG_SEGV), because of the app was accessing invalid memory zones. Hope it saves someone a couple of hours :)

mog2.cpp:

#include <opencv2/opencv.hpp>

cv::BackgroundSubtractorMOG2 mog(100, 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(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);
}

Compile it like:

gcc -shared -o libmog2.so -fPIC ./mog2.cpp -lopencv_core -lopencv_highgui -lopencv_objdetect -lopencv_imgproc -lopencv_features2d -lopencv_ml -lopencv_calib3d -lopencv_contrib -lopencv_video

And then python:

mog2.py

import numpy as np
import ctypes as C
import cv2

libmog = 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 res


def 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 res


if __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)
2013-10-09

相关问答

更多

python 引用from sklearn.model_selection import train_test_s报错

有可能是没安装PyWin32(网上搜来安装一下,是exe类型的)

绘画背景从TSeStyleFont(painting background from TSeStyleFont)

如果要绘制按钮的背景,则必须使用StyleServices.DrawElement方法传递正确的TThemedButton部分。 试试这个样本 uses Vcl.Styles, Vcl.Themes; {$R *.dfm} procedure TForm2.Button1Click(Sender: TObject); var Details : TThemedElementDetails; begin Details := StyleServices.GetElementDet ...

Python模块中的多个类(Multiple classes in a Python module)

以下是我见过的典型Java项目的一个有用的经验法则: Java中最底层的包应该是Python中的文件 那是什么意思? 如果你的Java项目是有组织的: toplevel/ subproject/ Foo.java Bar.java subproject2/ Baz.java Qux.java 那么你的Python项目应该如下所示: toplevel/ subproject.py <-- put class Foo ...

将libsvm模型结构从matlab保存到可以用C ++读取的.model文件中(Saving libsvm model structure from matlab to .model file which can be read in C++)

我修改了如何为回归创建libsvm的训练数据(作为svm_node结构体)的代码 ,并且看到了模型保存的格式 {struct svm_parameter param; // set by parse_command_line struct svm_problem prob; // set by read_problem // struct svm_model * model; struct svm_node * x_space; int main(int argc, const char * ar ...

将Django Model对象转换为所有字段完整的dict(Convert Django Model object to dict with all of the fields intact)

将实例转换为字典有许多方法,具有不同程度的角位处理和逼近所需的结果。 一个instance.__dict__ instance.__dict__ 这返回 {'_reference1_cache': <OtherModel: OtherModel object>, '_state': <django.db.models.base.ModelState at 0x1f63310>, 'created': datetime.datetime(2014, 2, 21, 4, 38, 51, 8447 ...

如何将绑定模型从视图传递回(非httppost)控制器方法(How to pass back binded model from view to (non-httppost) controller method)

只需将您的EditorFor内容包装在一个使用的Html.BeginForm()语句中,从您的按钮中删除Javascript,然后将按钮更改为提交类型,而不是编写自己的查询字符串。 @using (Html.BeginForm("GetStuff", "Controller", FormMethod.Get) { @Html.EditorFor(model => model.Name) @Html.DisplayFor(model ...

Ember.js从控制器调用模型的方法(Ember.js Calling model's method from controller)

我不确定您希望在方法中存在哪个上下文,如果您需要切换上下文,可以使用call / apply。 上下文应该是方法的上下文,而不是javascript标准的控制器。 var model = this.get('model'); model.methodName(arg1, arg2); 控制器的上下文 model.methodName.apply(this, arrayOfArgs); model.methodName.call(this, arg1, arg2); I'm not sure ...

相关文章

更多

最新问答

更多
  • Android宽度:100%修复(网站接管问题)(Android width:100% fix (website takeover issue))
  • C ++函数/方法设计的良好实践(Good practice in C++ function/method design)
  • 计算其他表中不存在的所有记录 - SQL查询(Count all records that does not exist to other table - SQL Query)
  • 为什么我要用JPA共享ID?(Why do I get shared Ids with JPA?)
  • asp.net - 如何显示来自html格式的数据行的字段(asp.net - how to display a field from data row that is in html format)
  • 我们如何使用ActiveRecord从连接表中删除行?(How can we delete rows from a join table by using ActiveRecord?)
  • ng-class搞乱了类的顺序(ng-class messing with the order of classes)
  • oracle 12g无效数字错误(oracle 12g invalid number error)
  • 更改ng-src值onclick(Change ng-src value onclick)
  • 如何在android中自动添加自定义依赖项以创建新项目?(How to add custom dependencies automatically in android for ever a new project is created?)
  • datetime函数在PHP中(datetime function in php)
  • 在javascript中获取会话数组的值(in javascript get the value of a session array)
  • 如何在UTF8中编译LaTeX?(How can I compile LaTeX in UTF8? [closed])
  • Rspec:“array.should == another_array”,但不用担心订单(Rspec: “array.should == another_array” but without concern for order)
  • Logcat错误:无法在android片段中加载视图(Logcat error: unable to load view in android fragments)
  • JavaFX的。(JavaFX. Adding items to the list in different threads is not working)
  • 从GDATA日历资源迁移到Google Calendar Resource api(Migrate from GDATA calendar resource to Google Calendar Resource api)
  • SSRS 2008 - 以零情景处理分割(SSRS 2008 - Dealing with division by zero scenarios)
  • 我如何以编程方式添加一个listView列标题的点击事件(How can I add a listView column header a click event programmatically)
  • Wxpython:无法检索有关列表控件项XXX的信息(Wxpython: Couldn't retrieve information about list control item XXX)
  • 使用Tortoise SVN在SVN存储库中移动目录(Move Directory across SVN repository using Tortoise SVN)
  • 天蓝色服务结构集群中的web api无状态服务是否在一段时间不活动后进入休眠状态?(Do web api stateless services in azure service fabric cluster go to sleep after a period of inactivity?)
  • 我可以设置intelliJ来突出显示PHP编码风格吗?(Can I set intelliJ to highlight php coding style?)
  • 用javafx创建一个Truetype字体文件(Creating a Truetype Font file with javafx)
  • Spring ftp配置错误(Spring ftp configuration is wrong)
  • 使用gsub去除多个字符(Using gsub to strip multiple characters)
  • 续订推送证书并保持当前的App Store App正常工作(Renew Push certificate and keep current App Store App working)
  • js:ES5和ES6之间关于'this'关键字用法的一个令人困惑的观点(js: one confusing point about 'this' keyword usage between ES5 and ES6)
  • window.onload vs $(document).ready()(window.onload vs $(document).ready())
  • 在Swift中,如何声明一个符合一个或多个协议的特定类型的变量?(In Swift, how can I declare a variable of a specific type that conforms to one or more protocols?)