Python adds mask to the image and extracts the instance of mask area


Python extracts the mask part of the image:


import os
import cv2
import numpy as np

def add_mask2image_binary(images_path, masks_path, masked_path):
# Add binary masks to images
  for img_item in os.listdir(images_path):
    img_path = os.path.join(images_path, img_item)
    img = cv2.imread(img_path)
    mask_ path =  os.path.join (masks_ path, img_ Item [: - 4] + '. PNG'). Mask is in. PNG format, and image is in. JPG format
    mask = cv2.imread(mask_ path, cv2.IMREAD_ Grayscale) read the color mask as a binary image
    masked = cv2.add(img,  np.zeros ( np.shape (img), dtype= np.uint8 ), mask = mask) ා add the pixel value of image and mask pixel value to get the result
    cv2.imwrite(os.path.join(masked_path, img_item), masked)
images_path = '/home/xinan/cat_test/image/'
masks_path = '/home/xinan/cat_test/catmask/'
masked_path = '/home/xinan/cat_test/masked/'
add_mask2image_binary(images_path, masks_path, masked_path)

design sketch:




In the above article, python adds mask to the image and extracts the example of mask area, which is all the content shared by Xiaobian. I hope it can give you a reference, and I hope you can support developer more.