Change language

Subtracting the background in an image using a moving average concept

| | |

In this article, we discuss the concept of a moving average . The moving average of the function is used to separate the foreground from the background. In this concept, a video sequence is analyzed over a specific set of frames. During this sequence of frames, a moving average is calculated for the current frame and previous frames. This gives us a background model, and any new object introduced during the video sequence becomes part of the foreground. Then the current frame contains the newly entered object with the background. It then calculates the absolute difference between the background model (which is a function of time) and the current frame (which is the newly entered object). The moving average is calculated using the equation below:


Prerequisites :

  • A working webcam or camera module for input.
  • Download Python 3.x, Numpy and OpenCV 2.7.x versions. Check if your OS is 32-bit or 64-bit compatible and install accordingly.
  • Check the status of NumPy and OpenCV

How does the moving average method work?

The purpose of the program is to detect active objects from the difference obtained from the keyframe and the current frame. We continue to feed each frame to this function, and the function continues to find the average of all frames. We then calculate the absolute difference between frames. 
Function used —  cv2.accumulate>Weighted () .

  cv2.accumulateWeighted (src, dst, alpha)  

Parameters passed to this function:

  1. CSI: Original image. The image can be color or grayscale, or 8-bit or 32-bit floating point.
  2. dst : accumulator or target image. It is 32 bit or 64 bit floating point. 
    NOTE. It should have the same channels as the original image. In addition, the dst value must be pre-declared initially.
  3. alpha : The weight of the input image. Alpha decides the update rate. If you set a smaller value for this variable, the moving average will be performed for more previous frames and vice versa.

Code :

# Python program to illustrate
# Subtract background with
# concept of running averages

# arrange imports

import cv2

import numpy as np

# capture camera frames

cap = cv2. VideoCapture ( 0 )

# read frames from the camera

_, img = ()

# change data type
# set 32-bit floating point

averageValue1 = np.float32 (img)

# loop starts if capture was initiated.

while ( 1 ):

# reads frames from the camera

_, img = ()


# using the cv2.accumulateWeighted () function

  # which updates the moving average

cv2.accumulateWeighted (img, averageValue1, 0.02 )


  # convert matrix elements to absolute values ​​

# and convert the result to 8-bit.

  resultingFrames1 = cv2.convertScaleAbs (averageValue1)


# Show two output windows

# input / source window

  cv2.imshow ( ’ InputWindow’ , img)


# window with alpha value 0.02

  cv2.imshow ( ’averageValue1’ , resultingFrames1)


# Wait until the Esc key stops the program

k = cv2.waitKey ( 30 ) & amp ;  0xff

if k = = 27


# Close the window
cap .release () 

# Unallocate any associated memory usage
cv2.destroyAllWindows ()


As we can see below, the hand is blocking the background image.

T Now we shake the foreground object, i.e. our hand. We start to wave our hand.

The Moving Average shows the background below, and the Moving Average with alpha 0.02 perceives it as a transparent hand with the main emphasis on the background.

Alternatively we can use cv.RunningAvg () for that same task with parameters that have the same meaning as cv2.accumulateweighted () parameters.

  cv.RunningAvg (image, acc, alpha)  

Recommendations :

  3. dc5 / tutorial_background_subtraction.html


Learn programming in R: courses


Best Python online courses for 2022


Best laptop for Fortnite


Best laptop for Excel


Best laptop for Solidworks


Best laptop for Roblox


Best computer for crypto mining


Best laptop for Sims 4


Latest questions


psycopg2: insert multiple rows with one query

12 answers


How to convert Nonetype to int or string?

12 answers


How to specify multiple return types using type-hints

12 answers


Javascript Error: IPython is not defined in JupyterLab

12 answers



Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method