Search code examples
pythonopencvimage-processingoverlaymask

How to overlay image mask onto the original image but show only the mask bounding box?


I have a folder containing hundreds of images and another folder with their corresponding masks. Both the images and the masks are named alike, for e.g. the mask for image1.png is also named as 'image1.png'. All images are grayscale.

enter image description here

I need to overlay the masks onto the original images in a loop but only show the masks bounding boxes, while making the inner surface of the mask completely transparent to show the original image regions as shown above. The current code reads the folder containing images and the masks but I need help with the overlay as requested.

import pandas as pd
import cv2
import numpy as np
import glob
import os
images = glob.glob("images\*.png")
masks = glob.glob("masks\*.png")
images.sort()
masks.sort()
for f1,f2 in zip(images,masks):
    img1 = cv2.imread(f1)
    img2 = cv2.imread(f2)
    img_1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
    img_2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
    img_name = f2.split(os.sep)[-1]
    contours, _ = cv2.findContours(img_2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    combined = cv2.drawContours(img_1, contours, -1, (0,255,0),1)
    cv2.imwrite("combined/{}.png".format(img_name[:-4]),combined) 

Solution

  • I found the issue. I need to use Zip in the for loop. I have corrected the code accordingly.