Background Subtraction in an Image using Concept of Running Average
Background subtraction
Running Average
Prerequisites :
- A working web camera or a camera module for input.
- Download Python 3.x, Numpy and OpenCV 2.7.x version. Check if your OS is either 32 bit or 64 bit compatible and install accordingly.
- Check the running status of numpy and OpenCV
How Running Average method works?
cv2.accumulateWeighted()
cv2.accumulateWeighted(src, dst, alpha)
- src: The source image. The image can be colored or grayscaled image and either 8-bit or 32-bit floating point.
- dst: The accumulator or the destination image. It is either 32-bit or 64-bit floating point. NOTE: It should have the same channels as that of the source image. Also, the value of dst should be predeclared initially.
- alpha: Weight of the input image. Alpha decides the speed of updating. If you set a lower value for this variable, running average will be performed over a larger amount of previous frames and vice-versa.
Code:
# Python program to illustrate # Background subtraction using # concept of Running Averages # organize imports import cv2 import numpy as np # capture frames from a camera cap = cv2.VideoCapture( 0 ) # read the frames from the camera _, img = cap.read() # modify the data type # setting to 32-bit floating point averageValue1 = np.float32(img) # loop runs if capturing has been initialized. while ( 1 ): # reads frames from a camera _, img = cap.read() # using the cv2.accumulateWeighted() function # that updates the running average cv2.accumulateWeighted(img, averageValue1, 0.02 ) # converting the matrix elements to absolute values # and converting the result to 8-bit. resultingFrames1 = cv2.convertScaleAbs(averageValue1) # Show two output windows # the input / original frames window cv2.imshow( 'InputWindow' , img) # the window showing output of alpha value 0.02 cv2.imshow( 'averageValue1' , resultingFrames1) # Wait for Esc key to stop the program k = cv2.waitKey( 30 ) & 0xff if k = = 27 : break # Close the window cap.release() # De-allocate any associated memory usage cv2.destroyAllWindows() |
Output :
cv.RunningAvg()
cv.RunningAvg(image, acc, alpha)
References
- https://docs.opencv.org/2.4/modules/imgproc/doc/motion_analysis_and_object_tracking.html
- https://en.wikipedia.org/wiki/Foreground_detection
- https://docs.opencv.org/3.2.0/d1/dc5/tutorial_background_subtraction.html
Contact Us