Background Subtraction OpenCv Python

Background Subtraction


Background Subtraction is a method in image processing in which we subtract the background to detect the object or more specifically changes in the environment. We will create a python code with simple mathematical operations to create background subtraction.


The way background subtraction work is we directly subtract background image from input image and then we binarize the image and after some operations like gaussian blur and erosion we get the object.

Take 2 images, one background image and one with the object. The idea here is we are working with stable non movable camera. This type of camera are generally used for security. 

Read the images in python using cv2.imread command then resize the images to desired size(resizing is always very helpful). 

background = cv2.imread('background.jpg')
image = cv2.imread('testforground.jpg')
shape = (200200)
bg = cv2.resize(background, shape)

Convert them to gray scale and then take difference of 2 images, you might have thought to  subtract images but it is not good way as negative difference in images is considered as 0 so instead of getting we might get a black screen. 

sub_image = gray_scale_bg - gray_scale_image

To tackle this we use absolute difference, there is a function available for absolute difference in OpenCV. Then binarize image and we will get the mask of object. 

abssub_img = cv2.absdiff(gray_scale_bggray_scale_image)
 

Now apply gaussian blur to remove the noise and use cv2.threshold to binarize image. Apply erosion and we get the object in binary image.
kernel = np.ones((99), np.uint8) 
gausian = cv2.GaussianBlur(abssub_img,(3,3),0 )
_, binary = cv2.threshold(gausian, 50255, cv2.THRESH_BINARY)
eroded = cv2.erode(binary, kernel, iterations=1)



To get rgb object in black background use eroded image as a mask to the input image.

Comments

Popular posts from this blog

Opencv python object detection Tutorial (part 1)