Python implements mask masking on images

Image mask : Use the selected image, figure or object to block the image to be processed (partial or all) 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 is a lot of demand for masking the image. Next, I will demonstrate with the following picture of a cat and dog. I chose Portrait of a kitten.

First look at the renderings:

 

Import the required libraries

The library resources required this time are available cv2and numpycan pip install xxxbe downloaded through.

import cv2
import numpy as np

Create a mask image

To create a mask, you need to look at the size of the image. You can 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 have 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

round 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)

The mask is stitched with the original image

Image merging uses cv2.add to merge the mask with the original image.

image = cv2.add(img, np.zeros(np.shape(img), dtype=np.uint8), mask=mask)

show images

# 展示原图
cv2.imshow("img", img)
# 展示掩膜图片
cv2.imshow("mask", mask)
# 展示添加掩膜效果图片
cv2.imshow("image", image)

Show results

Original image:

Square mask Image:

Square mask merged with original Image:

Circle mask Image:

Circle mask merged with original Image:

 

Summarize

The principle of the occlusion mask is very simple. First, create an all-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 superimpose the image and mask to achieve the occlusion display of the image.

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326569131&siteId=291194637