Rich's Wordpress

又一个WordPress站点

OpenCV 11: Masking

Select an image to mask on, and create a blank image to create the shape of the mask.

import cv2 as cv
import numpy as np

img = cv.imread('/Users/richzha/Desktop/CV/Image/Cat4.jpg')
cv.imshow('Cat', img)

blank = np.zeros(img.shape[:2], dtype='uint8')
cv.imshow('Blank',blank)

Create a circle and rectangle mask respectively.

circle_mask = cv.circle(blank.copy(),(img.shape[1]//2, img.shape[0]//2), 100,255,-1)
cv.imshow('Circle Mask',circle_mask)

rectangle_mask = cv.rectangle(blank.copy(), (img.shape[1]//2-85, img.shape[0]//2-85),(img.shape[1]//2+85, img.shape[0]//2+85), 255, -1)
cv.imshow('Rectangle Mask', rectangle_mask)

Use bit operation to combine the mask and the image.

mask = cv.bitwise_or(circle_mask,rectangle_mask)
cv.imshow('Mask', mask)

masked = cv.bitwise_and(img,img,mask=mask)
cv.imshow('Masked Image', masked)

cv.waitKey(0)
OpenCV 11: Masking
Scroll to top