How to calculate pixel number of foreground area in background subtraction

260 Views Asked by At

I have created a segmentation using the background subtraction technique. The next step I want to do is to eliminate the foreground area that has a number of pixels < 20. the question is how to count the number of pixels in each foreground area in a frame?example frame

1

There are 1 best solutions below

0
Hadi GhahremanNezhad On

You can use findContours and contourArea. Something like this:

import cv2 as cv
import numpy as np

# change 0 to 1 for shadow detection
backSub = cv.createBackgroundSubtractorMOG2(500,16,0)

capture = cv.VideoCapture("path/to/video.mp4")
if not capture.isOpened():
    print('Unable to open video')
    exit(0)

while True:
    ret, frame = capture.read()
    if frame is None:
        break
    
    fgMask = backSub.apply(frame)
    
    cv.rectangle(frame, (10, 2), (100,20), (255,255,255), -1)

    # this part is what you are looking for:
    contours, hierarchy = cv.findContours(fgMask, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
    
    # create an empty mask
    mask = np.zeros(frame.shape[:2],dtype=np.uint8)

    # loop through the contours
    for i,cnt in enumerate(contours):
        # if the size of the contour is greater than a threshold
        if  cv.contourArea(cnt) > 20:
            cv.drawContours(mask,[cnt], 0, (255), -1)
    
    cv.imshow('Frame', frame)
    cv.imshow('FG Mask', fgMask)
    cv.imshow("Mask", mask)
    
    keyboard = cv.waitKey(30)
    if keyboard == 'q' or keyboard == 27:
        break