0

enter image description here

I have a binary mask, how to apply a Gaussian kernel of standard unit deviation on the border of the mask to smooth border?

Community
  • 1
  • 1

1 Answers1

2

When applying Gaussian blur filter on a mask, it blurs only the borders of the mask.

Example:

import cv2
orig_img = cv2.imread('mask.png', cv2.IMREAD_GRAYSCALE)  # Read image as Grayscale.
blur = cv2.GaussianBlur(orig_img, (15, 15), 0)

Result:
enter image description here


In case you want to keep the mask unmodified, and smooth only the pixels around the mask, I suggest using few iterations, and taking the maximum.

Getting the maximum between the original image and blurred image, makes sure that the original mask pixels remains unchanged, because their values is 255 (maximum possible value).

Here is a code sample:

import cv2

orig_img = cv2.imread('mask.png', cv2.IMREAD_GRAYSCALE)  # Read image as Grayscale.

img = orig_img.copy()
for i in range(10):
    blur = cv2.GaussianBlur(img, (15, 15), 0)
    img = cv2.max(blur, img)  # Getting the maximum in order to mask the margins brighter

blur = cv2.max(orig_img, img)  # Getting the maximum for keeping the original mask pixels unmodified.

cv2.imshow('blur', blur)
cv2.waitKey()
cv2.destroyAllWindows()

Result:
enter image description here


Another option is using morphological dilation before GaussianBlur:

import cv2

orig_img = cv2.imread('mask.png', cv2.IMREAD_GRAYSCALE)  # Read image as Grayscale.

img = cv2.dilate(orig_img, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7)))

blur = cv2.GaussianBlur(img, (15, 15), 0)

blur = cv2.max(blur, orig_img)  # Getting the maximum for keeping the original mask pixels unmodified.

cv2.imshow('blur', blur)
cv2.waitKey()
cv2.destroyAllWindows()

Result:
enter image description here

Rotem
  • 30,366
  • 4
  • 32
  • 65