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

Jen*_*nny 2 python opencv image-processing

目标是模糊图像中选定对象的边缘。

我已经使用以下代码完成了获取对象轮廓的步骤:

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)
Run Code Online (Sandbox Code Playgroud)

我还可以使用以下方法绘制轮廓:

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

现在我想利用存储的点contours来模糊/羽化对象的边缘,也许使用高斯模糊。我怎样才能做到这一点?

非常感谢!

Chr*_*nry 6

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

  • 加载原始图像并找到轮廓。
  • 模糊原始图像并将其保存在不同的变量中。
  • 创建一个空的蒙版并在其上绘制检测到的轮廓。
  • 使用 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)
Run Code Online (Sandbox Code Playgroud)

原图

检测到的轮廓

边缘模糊

  • 注意:threshold()调用之后的“[2]”一定会失败,因为threshold()只返回两个东西。我找不到表明这曾经是其他任何东西的文档。最好只写“(rv, thresh) = cv.threshold...” (2认同)