Search code examples
pythonopencvimage-processingbounding-box

Converting Bounding box regions into masks and saving them as PNG files


I have a set of images with their bounding box values as shown below:

image_names class   xmin    xmax    ymin    ymax
image1.png  1       260     361     45      184

I wish to convert these bounding box values into a mask having the bounding box dimensions and filled with white pixels and store the masks for each image in the format "image1_mask.png" and so on. Do we have predefined functions to do this?


Solution

  • Simple approach

    import cv2
    import numpy as np
    
    img = cv2.imread('image1.png') # read image
    mask = np.zeros((img.shape[0],img.shape[1]),dtype=np.uint8) # initialize mask
    mask[ymin:ymax,xmin:xmax] = 255 # fill with white pixels
    cv2.imwrite('image1_mask.png',mask) # save mask