How do I remove a shadow after MOG2 background subtraction using OpenCV Python? I used all morphological operations, gaussian and median blur, thresholding. it removes noises but deep shadow is resulting in foreground object. enter image description here


2 Answers 2

fgbg = cv2.createBackgroundSubtractorMOG2(128,cv2.THRESH_BINARY,1)
masked_image = fgbg.apply(image)

in masked_image shadow will be grey color(pixel value= 127) just replace 127 to 0, to convert grey pixel to black.

  • $\begingroup$ I have same problem. Is there any suggestion for stile image? Thanks $\endgroup$
    – Learning
    Commented Nov 1, 2019 at 7:12

OpenCV has many different Background subtraction models.

If you use: cv2.BackgroundSubtractorMOG it will produce foreground without any shadows.

If you use: cv2.BackgroundSubtractorMOG2 it will produce foreground with shadows included. However, they are grey color.

So if you look at the foreground mask - following rule applies:

pixel[i][j] == 0 --> background
pixel[i][j] == 256 --> foreground
else pixel[i][j] == anyother value --> shadow.

See this for reference.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.