如何使用Opencv在图像中模糊/羽化对象的边缘?

3

本文旨在模糊图像中所选对象的边缘。

我已经通过以下代码获取了对象的轮廓:

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)

我也可以使用以下代码来绘制轮廓:

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

现在我想利用存储在contours中的点来对物体的边缘进行模糊/羽化处理,可以使用高斯模糊。如何实现呢?

非常感谢!

1个回答

16

与我之前在这里提到的类似,您可以按照以下步骤进行:

  • 加载原始图像并查找轮廓。
  • 模糊原始图像并将其保存在不同的变量中。
  • 创建一个空遮罩并在其上绘制检测到的轮廓。
  • 使用np.where()方法选择您想要模糊值的遮罩(轮廓)中的像素,然后替换它们。

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)

原始图片

检测轮廓

模糊边缘


2
请注意:在threshold()调用之后的[2]注定会失败,因为threshold()只返回两个值。我找不到任何文档显示它曾经是其他东西。最好写成(rv, thresh) = cv.threshold... - Christoph Rackwitz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接