Improve coverage of BackgroundSubtractorMOG2 and findContours I'm trying to track players on a soccer field, using a fixed camera. The picture below shows the results of BackgroundSubtractorMOG2, the second picture below the results of findContours on the results of BackgroundSubtractorMOG2.

As you can see there are a lot off small contours detected. How can a I alter the results of BackgroundSubtractorMOG2 so one shape (a player) results in one contour I can track ?


This is the code I used:

import numpy as np
import cv2

cap = cv2.VideoCapture("images/Keeper.mov")
history = 30   # or whatever you want it to be
accelerate = 5

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
fgbg = cv2.BackgroundSubtractorMOG2()

while(1):
    for i in (1, accelerate):
        ret, frame = cap.read()

    fgmask = fgbg.apply(frame, learningRate=1.0/history)

    fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)
    cv2.imshow('frame',fgmask)

    h, w = fgmask.shape[:2]

    contours0, hierarchy = cv2.findContours( fgmask.copy(), cv2.RETR_TREE, 
    cv2.CHAIN_APPROX_SIMPLE)
    contours = [cv2.approxPolyDP(cnt, 3, True) for cnt in contours0]

    vis = np.zeros((h, w, 3), np.uint8)
    levels = 17
    cv2.drawContours( vis, contours, (-1, 3)[levels &lt;= 0], (128,255,255),
            -1, cv2.CV_AA, hierarchy, abs(levels) )
    cv2.imshow('contours', vis)

    k = cv2.waitKey(30) &amp; 0xff
    if k == 27:
        break

cap.release()
cv2.destroyAllWindows()
I'm not an expert in this field, but have you tried eroding and then dilating?
I'm writing a python application to track tennis players in the court, and what I did in order to get a single contour for the players is to erode and dilate the tracked shapes.

erosion = cv2.erode(img,None,iterations = 1);
dilation = cv2.dilate(erosion,None,iterations = 1);
cv2.findContours( dilation.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE);


or you can directly call the function

opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel);
cv2.findContours( opening.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE);


Source: OpenCv Morphological Transformations