0

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

fmw42
  • 46,825
  • 10
  • 62
  • 80
  • OpenCV has a findContours and a connectedComonents function which (either of them) can give you a list of different "areas". You might want to use dilates and erodes to improve your mask (e.g. to connnect the head to the body) before extracting areas, but can be challenging to find good parameters. For each area then you can use contourArea function or count non black pixels. – Micka Nov 08 '21 at 13:00
  • Please provide enough code so others can better understand or reproduce the problem. – Community Nov 08 '21 at 16:28

1 Answers1

0

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
Hadi GhahremanNezhad
  • 2,377
  • 5
  • 29
  • 58