Search code examples
c++opencvsensorsmotion-detection

how to use openCV as a motion detector (not looking for video output)


I'm very new to c++ and have been doing a lot of research into openCV. I'm currently making a motion detector using a webcam and trying to use it to trigger a function (kind of like a listener). I don't need any kind of visual video in my application. I just need to sense motion and give an output like a boolean for instance.

I am much more familiar with java but it has to be written in c++, no wrappers, no converters.

Can someone please help point me in the write direction. maybe with a tutorial or suggestion of something I should look up. Even a different library I should use rather than openCV.


Solution

  • As a starting point, I'd recommend using a basic image subtraction then take it from there.

    The basic algorithm is:

    firstFrame = readFrame()
    
    firstFrameGrey = convertToGreyScale(firstFrame) // makes the image B&W
    
    while True
    
        secondFrame = readFrame()
        secondFrameGrey = convertToGreyScale(secondFrame)
    
        difference = sub(firstFrameGrey, secondFrameGrey)
    
        threshold()
    
        // perform some morphological operations
        erosion()
        dilation()
    
        findContours()
    
    // loop over contours and try filtering based off of area, perimeter etc.
    // This filtration will allow you to detect significant changes.
    
    // update frame
    firstFrameGrey = secondFrameGrey
    

    For the morphological operations, experiment with different values and see what results you get.

    More info on thresholding

    This tutorial explains how to perform the morphological operations.

    Contours info can be found here along with the area API

    The algorithm should be self explanatory and openCV has all the methods I named.