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

I don't know whether it is the fastest way, but It is a way to do it.

Create a mask image with region of face as white, then apply bitwise_and function with original image and mask image.

x = y = 30
w = h = 100

mask = np.zeros(img.shape[:2],np.uint8)
mask[y:y+h,x:x+w] = 255
res = cv2.bitwise_and(img,img,mask = mask)

It takes 0.16 ms in my system (core i5,4GB RAM) for an image of size 400x300

EDIT - BETTER METHOD: You need not do as above. Simply create a zero image and then copy ROI from original image to zero image. that's all.

mask = np.zeros(img.shape,np.uint8)
mask[y:y+h,x:x+w] = img[y:y+h,x:x+w]

It takes only 0.032 ms in my system for above parameters, 5 times faster than above.

Results :

Input Image :

enter image description here

Output :

enter image description here

Tags:

Python

Opencv