如何使用Opencv模糊/羽化图像中对象的边缘? [英] How to blur/ feather the edges of an object in an image using Opencv?
本文介绍了如何使用Opencv模糊/羽化图像中对象的边缘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目标是使图像中所选对象的边缘模糊.
我已经使用以下代码完成了获取对象轮廓的步骤:
image = cv2.imread('图像路径')灰色= cv2.cvtColor(图像,cv2.COLOR_BGR2GRAY)thresh = cv2.threshold(灰色,60,255,cv2.THRESH_BINARY)[1]im,轮廓,层次结构= cv2.findContours(thresh.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
我还可以使用以下方式绘制轮廓:
cv2.drawContours(图片,轮廓,-1,(0、255、0),2)
现在,我想利用存储在 contours
中的点来模糊/羽化对象的边缘,也许使用高斯模糊.我该如何实现?
非常感谢!
解决方案
与我提到的内容类似
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!
解决方案
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)
这篇关于如何使用Opencv模糊/羽化图像中对象的边缘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文