1. 程式人生 > >Python3 AttributeError: module 'cv2' has no attribute 'createBackgroundSubtractorMOG'

Python3 AttributeError: module 'cv2' has no attribute 'createBackgroundSubtractorMOG'

問題:在用python3使用cv2.createBackgroundSubtractorMOG()的時候,可能會產生錯誤:AttributeError: module 'cv2' has no attribute 'createBackgroundSubtractorMOG'

import numpy as np
import cv2
cap = cv2.VideoCapture(0)
fgbg = cv2.createBackgroundSubtractorMOG()
while(1):
    ret, frame = cap.read()
    fgmask = fgbg.apply(frame)
    cv2.imshow('frame',fgmask)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break
cap.release()
cv2.destroyAllWindows()

報錯資訊:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-12-88fb5127ef25> in <module>()
      2 import cv2
      3 cap = cv2.VideoCapture(0)
----> 4 fgbg = cv2.createBackgroundSubtractorMOG()
      5 while(1):
      6     ret, frame = cap.read()

AttributeError: module 'cv2' has no attribute 'createBackgroundSubtractorMOG'

解決:將fgbg = cv2.createBackgroundSubtractorMOG()替換為:

              fgbg = cv2.createBackgroundSubtractorMOG2() 

分析:

        在python3中,缺少cv2.createBackgroundSubtractorMOG()方法改為了cv2.createBackgroundSubtractorMOG2()。

變更樣例:

fgbg = cv2.createBackgroundSubtractorMOG2()

 

說明:問題產生的環境
           Python版本:3.6.5
           OpenCV版本:3.4.2