Motion detection

OpenCV  Python  

We are going to achieve motion detection by background subtraction technique

5/5 (4)


Motion detection is useful for safety purposes.When you have a safety lock in your house,motion detection can help you detect if someone is inside your safety lock room.Its used in army for any movement near border.You can use motion detect to create your own solution for a problem that you face
in your life.

We are going to achieve motion detection by background subtraction technique.Can we detect motions when the camera is moving?.The answer is no as background subtraction works on static images.It means we can perform motion detection only from a still camera.Below image will give you a better understanding of how background subtraction works

Background model is the reference frame which has no motions.Difference between the background model and the current model gives the detected motion.The problem is that background subtraction techique is sensitive to lightning conditions,natural movements like tree movement due to wind,waves,shadows etc.There are many background subtraction algorithms.We will now implement a motion detection using MOG.We will also put bounding box around the detected object.
1.Python 3.5 or 3.6
2. OpenCV: Opencv Contrib (pip install opencv-contrib-python)
3. numpy —> ‘1.14.4’(pip install numpy)


1.We will import the packeges
2.We use Background SubtractorMOG algorithm from opencv library.
3.We apply the algorithm to the frames.
4..At first you will have some noises along the detected motion.
4.Inorder to remove those noises we can blur the frame and apply threshold.We will use gaussian blurring
here to remove the noises.
5.You will notice some black holes in the bakcground subtracted frame.You can fill those gaps by morphological transformations like dilate,erode.
6.Dilate is used to fill the hole gaps and erode is used to remove the outer layers of white images.Erosion
can be used to remove white noises that you can see in the above image.
7.You can change the parameters to get the desired output.You can change the kernel size and get your
desired output

I have attached the code.You can download the document.

Please rate this

Project URL(s)