Image mask : Use selected images, graphics or objects to occlude the image (partially or completely) to be processed to control the area or process of image processing. Since the specific image or object covered is called a mask, when doing image processing, there are many requirements for masking the image. Next, I will demonstrate with the following picture of cats and dogs. I chose Kitten's head.
First look at the renderings:
Python implements mask processing of images
Import the required libraries
The library resources needed this time are combined cv2
and numpy
can pip install xxx
be downloaded through .
import cv2
import numpy as np
Create mask image
To create a mask, you need to look at the size of the image, and create your own mask according to the size of the image. Of course, you can also choose the mask you want. The masks I created here include square masks and circular masks.
Square mask
The mask coordinates are [10:170, 50:220].
# 创建掩膜
mask = np.zeros([img.shape[0], img.shape[1]], dtype=np.uint8)
mask[10:170, 50:220] = 255
Circular mask
Mask coordinates:
x = 140
y = 100
r = 80
# 创建掩膜
x = 140
y = 100
r = 80
mask = np.zeros(img.shape[:2], dtype=np.uint8)
mask = cv2.circle(mask, (x, y), r, (255, 255, 255), -1)
Mask and original image stitching
Image merging uses cv2.add, which merges the mask with the original image.
image = cv2.add(img, np.zeros(np.shape(img), dtype=np.uint8), mask=mask)
Show image
# 展示原图
cv2.imshow("img", img)
# 展示掩膜图片
cv2.imshow("mask", mask)
# 展示添加掩膜效果图片
cv2.imshow("image", image)
Show results
Original image:
square mask image:
combined square mask and original image:
circular mask image:
combined circular mask and original image:
to sum up
The principle of the occlusion mask is very simple. First, create a black image of the same size as the picture, then change the pixels of the area to be displayed to white, and finally use cv2.add to overlay image and mask to achieve the occlusion display of the image.