analitics

Pages

Thursday, September 8, 2016

OpenGL and OpenCV with python 2.7 - part 003.

If you have seen the last tutorial about OpenCV, then this tutorial comes to complete with one source code.
This source code will cut the background of webcam.
The webcam output is take by VideoCapture function.
This part of source code: np.zeros((1,65),np.float64) will return a new array of given shape and type, filled with zeros.
The result of this parts is used with function grabCut from cv2 python module.
This is the source code:

import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
    ret, img = cap.read()
    #img = cv2.imread('test002.jpg')
    mask = np.zeros(img.shape[:2],np.uint8)

    bgdModel = np.zeros((1,65),np.float64)
    fgdModel = np.zeros((1,65),np.float64)

    rect = (50,50,450,290)
    cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)

    mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
    img = img*mask2[:,:,np.newaxis]
    cv2.imshow('frame',img)
    if 0xFF & cv2.waitKey(5) == 27:
        break
cap.release()
cv2.destroyAllWindows()
The end result will be something like: