Python cv2.BackgroundSubtractorMOG() Examples

The following are 6 code examples of cv2.BackgroundSubtractorMOG(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cv2 , or try the search function .
Example #1
Source File: motion_detection.py    From deepgaze with MIT License 6 votes vote down vote up
def __init__(self, history=10, numberMixtures=3, backgroundRatio=0.6, noise=20):
        """Init the color detector object.

        @param history lenght of the history
        @param numberMixtures The maximum number of Gaussian Mixture components allowed.
            Each pixel in the scene is modelled by a mixture of K Gaussian distributions.
            This value should be a small number from 3 to 5.
        @param backgroundRation define a threshold which specifies if a component has to be included
            into the foreground or not. It is the minimum fraction of the background model. 
            In other words, it is the minimum prior probability that the background is in the scene.
        @param noise specifies the noise strenght
        """
        self.BackgroundSubtractorMOG = cv2.BackgroundSubtractorMOG(history, numberMixtures, backgroundRatio, noise) 
Example #2
Source File: MOGSegmentation.py    From SimpleCV2 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, history = 200, nMixtures = 5, backgroundRatio = 0.7, noiseSigma = 15, learningRate = 0.7):
        
        try:
            import cv2            
        except ImportError:
            raise ImportError("Cannot load OpenCV library which is required by SimpleCV")
            return    
        if not hasattr(cv2, 'BackgroundSubtractorMOG'):
            raise ImportError("A newer version of OpenCV is needed")
            return            
        
        self.mError = False
        self.mReady = False        
        self.mDiffImg = None
        self.mColorImg = None
        self.mBlobMaker = BlobMaker()
        
        self.history = history
        self.nMixtures = nMixtures
        self.backgroundRatio = backgroundRatio
        self.noiseSigma = noiseSigma
        self.learningRate = learningRate
        
        self.mBSMOG = cv2.BackgroundSubtractorMOG(history, nMixtures, backgroundRatio, noiseSigma) 
Example #3
Source File: BackgroundRemove.py    From vidpipe with GNU General Public License v3.0 5 votes vote down vote up
def __init__ ( self ):
        super( BackgroundRemove, self ).__init__()
        self._name = "Background Remove"

        self._speed = 0.01
        self._avg = None

        self._fgbg = cv2.BackgroundSubtractorMOG() 
Example #4
Source File: motion_detection.py    From deepgaze with MIT License 5 votes vote down vote up
def returnMask(self, foreground_image):
        """Return the binary image after the detection process

        @param foreground_image the frame to check
        @param threshold the value used for filtering the pixels after the absdiff
        """
        return self.BackgroundSubtractorMOG.apply(foreground_image) 
Example #5
Source File: background_subtraction.py    From plantcv with MIT License 4 votes vote down vote up
def background_subtraction(background_image, foreground_image):
    """Creates a binary image from a background subtraction of the foreground using cv2.BackgroundSubtractorMOG().
    The binary image returned is a mask that should contain mostly foreground pixels.
    The background image should be the same background as the foreground image except not containing the object
    of interest.

    Images must be of the same size and type.
    If not, larger image will be taken and downsampled to smaller image size.
    If they are of different types, an error will occur.

    Inputs:
    background_image       = img object, RGB or binary/grayscale/single-channel
    foreground_image       = img object, RGB or binary/grayscale/single-channel

    Returns:
    fgmask                 = background subtracted foreground image (mask)

    :param background_image: numpy.ndarray
    :param foreground_image: numpy.ndarray
    :return fgmask: numpy.ndarray
    """

    params.device += 1
    # Copying images to make sure not alter originals
    bg_img = np.copy(background_image)
    fg_img = np.copy(foreground_image)
    # Checking if images need to be resized or error raised
    if bg_img.shape != fg_img.shape:
        # If both images are not 3 channel or single channel then raise error.
        if len(bg_img.shape) != len(fg_img.shape):
            fatal_error("Images must both be single-channel/grayscale/binary or RGB")
        # Forcibly resizing largest image to smallest image
        print("WARNING: Images are not of same size.\nResizing")
        if bg_img.shape > fg_img.shape:
            width, height = fg_img.shape[1], fg_img.shape[0]
            bg_img = cv2.resize(bg_img, (width, height), interpolation=cv2.INTER_AREA)
        else:
            width, height = bg_img.shape[1], bg_img.shape[0]
            fg_img = cv2.resize(fg_img, (width, height), interpolation=cv2.INTER_AREA)

    bgsub = cv2.createBackgroundSubtractorMOG2()
    # Applying the background image to the background subtractor first.
    # Anything added after is subtracted from the previous iterations.
    _ = bgsub.apply(bg_img)
    # Applying the foreground image to the background subtractor (therefore removing the background)
    fgmask = bgsub.apply(fg_img)

    # Debug options
    if params.debug == "print":
        print_image(fgmask, os.path.join(params.debug_outdir, str(params.device) + "_background_subtraction.png"))
    elif params.debug == "plot":
        plot_image(fgmask, cmap="gray")

    return fgmask 
Example #6
Source File: Input.py    From DanceCV with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def __init__(self, debug = False):
        
        self.capture = cv2.VideoCapture(0)
        if self.capture.isOpened():         # Checks the stream
            self.frameSize = (int(self.capture.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)),
                               int(self.capture.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)))        
        Constants.SCREEN_HEIGHT = self.frameSize[0]
        Constants.SCREEN_WIDTH = self.frameSize[1]
        self.bsmog = []
        self.bgAdapt = []

        history = 100 
        nGauss = 20 
        bgThresh = 0.2
        noise = 7
        
        for i in range(0,4):
            #self.bsmog.append(cv2.BackgroundSubtractorMOG())
            self.bsmog.append(cv2.BackgroundSubtractorMOG(history,nGauss,bgThresh,noise))
            self.bgAdapt.append(Constants.BG_ADAPT)
        
        self.debug = debug
        
        self.debugWindow0 = "Debug Window 0"
        self.debugWindow1 = "Debug Window 1"
        self.debugWindow2 = "Debug Window 2"
        self.debugWindow3 = "Debug Window 3"
        self.debugWindow4 = "Debug Window 4"
        self.debugWindow5 = "Debug Window 5"
        
        if self.debug:
            cv2.namedWindow(self.debugWindow0)
            cv2.namedWindow(self.debugWindow1)
            cv2.namedWindow(self.debugWindow2)
            cv2.namedWindow(self.debugWindow3)
            cv2.namedWindow(self.debugWindow4)
            cv2.namedWindow(self.debugWindow5)
        
        result, self.currentFrame = self.capture.read()        
        self.currentFrame = cv2.flip(self.currentFrame, 1)
        self.previousState = []
        self.currentState = []
        for i in range(0,4):
            self.saveBackground(self.currentFrame, i)
            self.previousState.append(False)
            self.currentState.append(False)
        self.t = False