OpenCV - Apply mask to a color image

pzo picture pzo · May 6, 2012 · Viewed 149k times · Source

How can I apply mask to a color image in latest python binding (cv2)? In previous python binding the simplest way was to use cv.Copy e.g.

cv.Copy(dst, src, mask)

But this function is not available in cv2 binding. Is there any workaround without using boilerplate code?

Answer

Abid Rahman K picture Abid Rahman K · May 6, 2012

Here, you could use cv2.bitwise_and function if you already have the mask image.

For check the below code:

img = cv2.imread('lena.jpg')
mask = cv2.imread('mask.png',0)
res = cv2.bitwise_and(img,img,mask = mask)

The output will be as follows for a lena image, and for rectangular mask.

enter image description here