How to blur/ feather the edges of an object in an image using Opencv?

↘锁芯ラ 提交于 2021-01-28 04:25:17

问题


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!


回答1:


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)



来源:https://stackoverflow.com/questions/55066764/how-to-blur-feather-the-edges-of-an-object-in-an-image-using-opencv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!