Image mask: Control the area or process of image processing by blocking the processed image (part or all) with the selected image, graph or object. As the specific images or objects covered are called masks, there are many requirements for image masking in image processing. The following picture of a cat and a dog is used for demonstration. I choose the head of a kitten.

First look at the renderings:



Import the required libraries

PIP install XXX can be used to download cv2 and numpy.

import cv2
import numpy as np
Copy the code

Create a mask image

Create a mask depends on the size of the image. Create your own mask according to the size of the image. Of course, you can also choose your own mask. The masks I created here have square masks and circular masks.

Square mask

The mask coordinates are [10:170, 50:220].

Shape [0], img.shape[1]], dType =np.uint8) mask[10:170, 50:220] = 255Copy the code

Circular mask

Mask coordinates: x = 140, Y = 100, r = 80

Uint8) mask = cv2.circle(mask, (x, y), r, (255, 255, 255), 1)Copy the code

The mask is spliced with the original image

Cv2. add is used for image merging, and the mask and the original image are spliced and merged.

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

Show the image

Imshow ("mask", mask) # show cv2.imshow("image", image) # show cv2.imshow("image", image) # show cv2.imshow("image", image) # show cv2.imshow("image", image) # show cv2.imshow("image", image)Copy the code

Results show

Original image:



Square mask image:



Image merged with square mask and original image:



Circular mask image:



Combined image of circular mask and original image:

conclusion

The principle of occlusion mask is very simple. First create an all-black image with the same size as the picture, then change the pixel of the region to be displayed to white, and finally use Cv2.add to overlay image and mask to realize occlusion display of the image.