OpenCV via python: Is there a fast way to zero pixels outside a set of rectangles?

Viewed 17697

I have an image of a face and I have used haar cascades to detect the locations (x,y,width,height) of the mouth, nose and each eye. I would like to set all pixels outside these regions to zero. What would be the fastest (computationally) way to do this? I'll eventually be doing it to video frames in real time.

2 Answers

If a polygon ROI is to be made. Create the polygon and make a mask for it. Multiply the image with the created frame.

    ret,frame = cv2.imread()
    xr=1
    yr=1
    # y,x
    pts = np.array([[int(112*yr),int(32*xr)],[int(0*yr),int(623*xr)],[int(789*yr),int(628*xr)],[int(381*yr),int(4*xr)]], np.int32)
    pts = pts.reshape((-1,1,2))
    cv2.polylines(frame,[pts],True,(0,255,255))

    mask = np.zeros(frame.shape[:2],np.uint8)
    cv2.fillPoly(mask,[pts],(255,255,255))
    frame = cv2.bitwise_and(frame,frame,mask = mask)
    cv2.imshow("masked frame", frame)
Related