Python implements masking processing on images, super detailed explanation! ! !

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:
Insert picture description here
Insert picture description here

Insert picture description here

Import the required libraries

The library resources needed this time are combined cv2and numpycan pip install xxxbe 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:
Insert picture description here
square mask image:
Insert picture description here
combined square mask and original image:
Insert picture description here
circular mask image:
Insert picture description here
combined circular mask and original image:

Insert picture description here

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.

Insert picture description here

Guess you like

Origin blog.csdn.net/ywsydwsbn/article/details/107644502