【问题标题】:How to save/write OpenCV EM/GMM model using Python?如何使用 Python 保存/编写 OpenCV EM/GMM 模型?
【发布时间】:2014-11-12 21:48:59
【问题描述】:

我想知道是否存在任何方法/函数可用于保存使用 Python 在 OpenCV 中定义的经过训练的 EM(Expectation Maximization 或高斯混合模型)模型?

我已经尝试过Pickle dump() 方法,但它不起作用。它显示一个错误:TypeError: can't pickle EM objects。此外,我还尝试了其他简单的方法,例如文件打开和写入(以 XML 格式)。但是,它也不起作用。

这是我的 Python 代码的一部分:

import cv2
import numpy as np
from sklearn import mixture

im = cv2.imread('001.png', False)
PCenter = [2,2]
pyrDown_img = im.copy()
X_train = []
gmm_clf = cv2.EM(12, cv2.EM_COV_MAT_DIAGONAL) # Initialize classifier object

for row in range(PCenter[0], pyrDown_img.shape[0] - PCenter[0]):
    for col in range(PCenter[1], pyrDown_img.shape[1] - PCenter[1]):

        patch = pyrDown_img[row-PCenter[0]:row+PCenter[0]+1, col-PCenter[1]:col+PCenter[1]+1]
        patch = np.asarray(patch) # compute patch as a feature vector
        X_train.append(patch.reshape(-1))

X_train = np.asarray(X_train)
gmm_clf.train(X_train) # train GMM classifier

我想将这个 gmm_clf 保存到一个文件中,以便以后用于测试目的。

【问题讨论】:

    标签: python opencv expectation-maximization


    【解决方案1】:
    mean = gmm_clf.getMat('means')
    cov = gmm_clf.getMatVector('covs')
    

    然后保存意思,cov with pickle。

    但是,您不能根据doc 中的最后一段gmm_clf.setMat('means')

    所以,你现在有两个选择:

    1. 修改opencv源码使均值和协方差不是只读的,然后重新编译cv2.so。

    2. 使用提取均值和 cov 预测您的数据。

    (我会选择2,这很容易。)

    【讨论】:

    • 非常感谢。是的,OpenCV for Python 中的 EM 似乎没有很好的定义。我使用了提供 GMM 模型实现的 sklearn 库,它运行良好。在那里,您可以使用 Pickle 保存模型并在以后随时重复使用。关于选择,他们都说得通。但是,我没有太多时间调查他们。
    【解决方案2】:

    我知道这是旧的,但我刚刚遇到这个,我很确定这种方法比使用泡菜更好。使用numpy.savez 或当空间存在问题时使用numpy.savez_compressed,例如:

    import cv2
    import numpy as np
    
    # say em is your trained cv2.EM()
    means   = np.float32(em.getMat("means"))
    covs    = np.float32(em.getMatVector("covs"))
    weights = np.float32(em.getMat("weights"))
    
    filepath = "gmm_coefficients.npz"
    np.savez(filepath, means=means, covs=covs, weights=weights)
    
    # then to load the file
    npzfile = np.load(filepath)
    means   = npzfile["means"]
    covs    = npzfile["covs"]
    weights = npzfile["weights"]
    

    【讨论】:

      猜你喜欢
      • 2020-12-04
      • 2011-09-07
      • 2012-05-21
      • 2014-06-22
      • 2016-11-18
      • 2021-06-26
      • 2014-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多