Search code examples
pythonopencvbounding-box

Set white color outside boundingBox (Python, OpenCV)


I have this image:

src

(or this..)

src2

How can I set to white all the area outside the boundingBox'es ?

I would like to obtain this result:

desired

Thanks


Solution

  • As mentioned in the comments if you have the positions of the ROIs, you can use them to paste them on the an image with white background having the same shape as the original.

    import cv2
    import numpy as np
    
    image = cv2.imread(r'C:\Users\Desktop\rus.png')
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    white_bg = 255*np.ones_like(image)
    
    ret, thresh = cv2.threshold(gray, 60, 255, cv2.THRESH_BINARY_INV)
    blur = cv2.medianBlur(thresh, 1)
    kernel = np.ones((10, 20), np.uint8)
    img_dilation = cv2.dilate(blur, kernel, iterations=1)
    im2, ctrs, hier = cv2.findContours(img_dilation.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    
    sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0])
    for i, ctr in enumerate(sorted_ctrs):
        # Get bounding box
        x, y, w, h = cv2.boundingRect(ctr)
        roi = image[y:y + h, x:x + w]
        if (h > 50 and w > 50) and h < 200:
    
            cv2.rectangle(image, (x, y), (x + w, y + h), (255, 255, 255), 1)        
            cv2.imshow('{}.png'.format(i), roi)
    
            #--- paste ROIs on image with white background 
            white_bg[y:y+h, x:x+w] = roi
    
    cv2.imshow('white_bg_new', white_bg)
    cv2.waitKey(0)
    cv2.destroyAllWindows() 
    

    The result:

    enter image description here