3

The objective is to blur the edges of a selected object in an image.

I've done the steps to obtain the contours of the object by using the following code:

image = cv2.imread('path of image')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 60, 255, cv2.THRESH_BINARY)[1]
im, contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

I am also able to plot the contour using:

cv2.drawContours(image, contours, -1, (0, 255, 0), 2)

Now I want to make use of the points stored in contours to blur / feather the edge of the object, perhaps using gaussian blur. How am I able to achieve that?

Thanks so much!

Jenny
  • 111
  • 2
  • 4
  • 10

1 Answers1

16

Similar to what I have mentioned here, you can do it in the following steps:

  • Load original image and find contours.
  • Blur the original image and save it in a different variable.
  • Create an empty mask and draw the detected contours on it.
  • Use np.where() method to select the pixels from the mask (contours) where you want blurred values and then replace it.

import cv2
import numpy as np

image = cv2.imread('./asdf.jpg')
blurred_img = cv2.GaussianBlur(image, (21, 21), 0)
mask = np.zeros(image.shape, np.uint8)

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 60, 255, cv2.THRESH_BINARY)[2]
contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

cv2.drawContours(mask, contours, -1, (255,255,255),5)
output = np.where(mask==np.array([255, 255, 255]), blurred_img, image)

Original image

Detected contours

Blurred edges

Chris Henry
  • 396
  • 2
  • 8
  • 2
    note: that `[2]` after the threshold() call is bound to fail because threshold() only returns two things. I can't find documentation that shows this ever having been anything else. best to just write `(rv, thresh) = cv.threshold...` – Christoph Rackwitz Jun 26 '22 at 00:04