Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

OpenCV Background Subtraction Get Color Objects (Python)

Background subtraction method (BackgroundSubtractorMOG2) will normally return the output in binary image.

Is there a solution on how I can get the original colour of the object after implementing the BackgroundSubtractorMOG2 ?

kernel_dil = np.ones((10,10), np.uint8)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
fgbg = cv2.createBackgroundSubtractorMOG2(history=0, varThreshold=444, detectShadows=False)

while True:
   ret, frame1 = cap.read()
   frame = cv2.resize(frame1,(1364,700),fx=0,fy=0, interpolation = cv2.INTER_CUBIC)

   mask = np.zeros(frame.shape, dtype=np.uint8)
   mask.fill(255)

   roi_corners = np.array([[(11,652), (1353,652), (940,84), (424,84)]], dtype=np.int32)
   mask = cv2.fillPoly(mask, roi_corners, 0)

   masking = cv2.bitwise_or(frame, mask)

   if ret == True:
        fgmask = fgbg.apply(masking,mask)
        fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)
        dilation = cv2.dilate(fgmask, kernel_dil, iterations = 1)
       (contours,hierarchy) = cv2.findContours(dilation, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

        for pic, contour in enumerate(contours):

           area = cv2.contourArea(contour)
           x,y,w,h = cv2.boundingRect(contour)

           if(area>0):
              cv2.rectangle(frame, (x,y), (x+w,y+h), (0,0,255), 2)
              cv2.putText(frame, 'People', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255,0,0), 2, cv2.LINE_AA)

This is my current output : Mask

Field