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?
To invert a mask in OpenCV, we use the cv2. bitwise_not() function, which performs bitwise not operation on individual pixels. Parameters: masked_image: It is the image that is to be inverted.
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.
Well, here is a solution if you want the background to be other than a solid black color. We only need to invert the mask and apply it in a background image of the same size and then combine both background and foreground. A pro of this solution is that the background could be anything (even other image).
This example is modified from Hough Circle Transform. First image is the OpenCV logo, second the original mask, third the background + foreground combined.
# http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghcircles/py_houghcircles.html import cv2 import numpy as np # load the image img = cv2.imread('E:\\FOTOS\\opencv\\opencv_logo.png') img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # detect circles gray = cv2.medianBlur(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY), 5) circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=50, minRadius=0, maxRadius=0) circles = np.uint16(np.around(circles)) # draw mask mask = np.full((img.shape[0], img.shape[1]), 0, dtype=np.uint8) # mask is only for i in circles[0, :]: cv2.circle(mask, (i[0], i[1]), i[2], (255, 255, 255), -1) # get first masked value (foreground) fg = cv2.bitwise_or(img, img, mask=mask) # get second masked value (background) mask must be inverted mask = cv2.bitwise_not(mask) background = np.full(img.shape, 255, dtype=np.uint8) bk = cv2.bitwise_or(background, background, mask=mask) # combine foreground+background final = cv2.bitwise_or(fg, bk)
Note: It is better to use the opencv methods because they are optimized.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With