pythonopencvmask

Creating a masked image with smooth borders using opencv and numpy


smooth mask

I'm trying to create a masked image (smooth rounded borders of 10x10 pixels) as shown here (created in photoshop) using opencv and numpy. Here is my code

import cv2
import numpy as np

# Create a 128x128 white image
mask = np.ones((128, 128), np.uint8) * 255

kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (10, 10))

# Erode the image to create a 10 pixel border
eroded_mask = cv2.erode(mask, kernel, cv2.BORDER_REFLECT, iterations=2)

# Apply Gaussian Blur to the eroded image
blurred_mask = cv2.GaussianBlur(eroded_mask, (21, 21), sigmaX=3, sigmaY=3, borderType=cv2.BORDER_DEFAULT)

# Display various images to see the steps
cv2.imshow('result', blurred_mask)
cv2.waitKey(0)
cv2.destroyAllWindows()

This code is not working as expected. I'm getting a pure white image with no smooth borders. Any Pointers?


Solution

  • Did you look at each image in your steps?

    To do that properly, you need to change the borderType to constant and make the constant value black.

    import cv2
    import numpy as np
    
    # Create a 128x128 white image
    mask = np.ones((128, 128), np.uint8) * 255
    
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (10, 10))
    
    # Erode the image to create a 10 pixel border
    eroded_mask = cv2.erode(mask, kernel, borderType = cv2.BORDER_CONSTANT, borderValue = 0, iterations=2)
    
    # Apply Gaussian Blur to the eroded image
    blurred_mask = cv2.GaussianBlur(eroded_mask, (21, 21), sigmaX=3, sigmaY=3, borderType=cv2.BORDER_DEFAULT)
    
    # Display various images to see the steps
    cv2.imshow('mask', mask)
    cv2.imshow('eroded_mask', eroded_mask)
    cv2.imshow('blurred_mask', blurred_mask)
    cv2.imwrite('blurred_mask.jpg', blurred_mask)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    enter image description here