Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

opencv

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.

like image 863
Mike Lawrence Avatar asked Jul 15 '12 13:07

Mike Lawrence


2 Answers

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

like image 134
Abid Rahman K Avatar answered Oct 21 '22 05:10

Abid Rahman K


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)
like image 21
Vinay Verma Avatar answered Oct 21 '22 06:10

Vinay Verma