2

I'm trying to use the default functions to do background subtraction of a video file.
I'm using Python 2.7 and OpenCV.
I receive this error when using the 'BackgroundSubtractorMOG' module:

'module' object has no attribute 'BackgroundSubtractorMOG'

Now, if I try using the createBackgroundSubtractorMOG() module, I receive the same error.
If I change my code to:

bkgnd = cv2.bgsegm.BackgroundSubtractorMOG()

I get an error later on that tries to tell me I'm using OpenCV 3.1 (although I'm fairly certain I'm not).

 img_sub_gray_image = cv2.cvtColor(img_sub, cv2.COLOR_BGR2GRAY) cv2.error:

/home/odroid/opencv-3.1.0/modules/imgproc/src/color.cpp:8000: error: (-215) scn == 3 || scn == 4 in function cvtColor

Here is the segment of code that is erroring out:

bkgnd = cv2.bgsegm.BackgroundSubtractorMOG() 
cap = cv2.VideoCapture('video.mp4')

while(True): 
    ret, frame = cap.read()

    #background subtraction
    img_sub = bkgnd.apply(frame)

    #convert to grayscale
    img_sub_gray_image = cv2.cvtColor(img_sub, cv2.COLOR_BGR2GRAY)
    #thresholding, forcing to binary image
    ret,threshold1 = cv2.threshold(img_sub_gray_image, LOWER_BOUND, UPPER_BOUND, cv2.THRESH_BINARY)

Any ideas?

Zoe
  • 27,060
  • 21
  • 118
  • 148
slow_one
  • 113
  • 1
  • 4
  • 13

3 Answers3

3

In opencv 3 they have changed some names of the functions, you must change:

bkgnd = cv2.bgsegm.BackgroundSubtractorMOG() 

to:

cv2.bgsegm.createBackgroundSubtractorMOG()

Another observation is that the result of the apply function is a binary image, so it is not necessary to do the conversion from RGB to gray. You do not need to use the command: cv2.cvtColor(img_sub, cv2.COLOR_BGR2GRAY)

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • After changing the line to: bkgnd = cv2.bgsegm.createBackgroundSubtractorMOG() I received this error: OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /home/odroid/opencv-3.1.0/modules/imgproc/src/color.cpp, line 8000 Traceback (most recent call last): File "FU_edge_detection_video_HoughLinesP.py", line 60, in img_sub_gray_image = cv2.cvtColor(img_sub, cv2.COLOR_BGR2GRAY) cv2.error: /home/odroid/opencv-3.1.0/modules/imgproc/src/color.cpp:8000: error: (-215) scn == 3 || scn == 4 in function cvtColor – slow_one Apr 26 '17 at 14:48
  • that got it. thank you. of course now I have other errors. But thanks for the help. – slow_one Apr 26 '17 at 15:08
0

This works well..

fgbg = cv2.BackgroundSubtractorMOG2()

P.S: I am using python 3.5 and cv2 version 3.3.1

Zoe
  • 27,060
  • 21
  • 118
  • 148
DataTales
  • 19
  • 1
  • 4
0

if you are using opencv 4 you should use MOG2 with history, varThreshold, detectShadows parameters

cv2.createBackgroundSubtractorMOG2(history=100,varThreshold=50,detectShadows=True)
Tolga Sahin
  • 319
  • 2
  • 6