def process_frame(frame, prev_mask, carpet_mask): if carpet_mask is None: carpet_mask = img_util.green_carpet_mask(frame, carpet_lowerb, carpet_upperb) mask = get_mask(frame, lowerb=ball_lowerb, upperb=ball_upperb, carpet_mask=carpet_mask) if prev_mask is None: move_mask = np.zeros_like(mask) else: move_mask = cv2.bitwise_not(prev_mask, mask=mask) prev_mask = mask is_ball, move_mask = img_util.detect_ball(move_mask) return is_ball, move_mask, prev_mask, frame
def extract_ball_from_capture(cap, max_frames_count=-1, skip_count=0, carpet_mask=None, get_mask=None, carpet_lowerb=None, carpet_upperb=None, ball_lowerb=None, ball_upperb=None, ball_size=3): """ Read frames from capture until we detect motion of the ball Return tuple of (original frames, ball mask frames) :param carpet_lowerb: :rtype : (list(np.ndarray), list(np.ndarray)) """ frames = [] mask_frames = [] # mog = cv2.BackgroundSubtractorMOG(history=5, nmixtures=4,backgroundRatio=0.7) mog = cv2.BackgroundSubtractorMOG() motion_started = False for _ in xrange(skip_count): if cap.isOpened(): cap.read() prev_mask = None while cap.isOpened(): if 0 < max_frames_count <= len(frames): logger.debug('max frames count reached') break ret, frame = cap.read() if ret: if get_mask is not None: if carpet_mask is None: carpet_mask = img_util.green_carpet_mask(frame, carpet_lowerb, carpet_upperb) mask = get_mask(frame, lowerb=ball_lowerb, upperb=ball_upperb, carpet_mask=carpet_mask) if prev_mask is None: move_mask = np.zeros_like(mask) else: move_mask = cv2.bitwise_not(prev_mask, mask=mask) prev_mask = mask else: logger.debug('get_mask = None') move_mask = mog.apply(frame) is_ball, move_mask = img_util.detect_ball(move_mask, ball_size) if is_ball: if not motion_started: logger.debug('ball appeared') motion_started = True frames.append(frame) mask_frames.append(move_mask) else: if motion_started: logger.debug( 'ball disappeared. Frames count: {}'.format( len(frames))) break else: continue else: logger.debug('Cannot read more frames') break return frames, mask_frames