添加两个边缘融合的图像

时间:2019-07-12 10:58:59

标签: python opencv

我正在编写一个脚本来检测人脸并模糊除人脸以外的所有东西。

我使用Haar级联找到面孔,然后为面孔所在的圆圈创建一个蒙版。然后,我将它们加在一起。这对于添加绝对分界点的效果很好,但是我无法弄清楚如何在没有钝线的情况下逐渐缩小模糊。模糊蒙版只会在逐渐变细的地方创建一条难看的线。

import numpy as np
import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

original_image = cv2.imread('person.jpg')
gray_original_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)

# mask
# detect faces and create mask
mask = np.full(
    (original_image.shape[0], original_image.shape[1], 1), 0, dtype=np.uint8)
faces = face_cascade.detectMultiScale(gray_original_image, 1.3, 5)
face_areas = []
for (x, y, w, h) in faces:
    face_areas.append(([x, y, w, h], original_image[y:y+h, x:x+w]))
    center = (x + w // 2, y + h // 2)
    radius = max(h, w) // 2
    cv2.circle(mask, center, radius, (255), -1)

# blur original image
kernel = np.ones((5, 5), np.float32) / 25
blurred_image = cv2.filter2D(original_image, -1, kernel)
# blur mask to get tapered edge
mask = cv2.filter2D(mask, -1, kernel)

# composite blurred and unblurred faces
mask_inverted = cv2.bitwise_not(mask)
background = cv2.bitwise_and(
    blurred_image, blurred_image, mask=mask_inverted)
foreground = cv2.bitwise_and(original_image, original_image, mask=mask)

composite = cv2.add(background, foreground)

cv2.imshow('composite', composite)
cv2.waitKey(0)
cv2.destroyAllWindows()

原始 enter image description here

脚本输出 enter image description here

所需结果(模糊/不模糊之间没有明显的界线) enter image description here

1 个答案:

答案 0 :(得分:0)

您完成了大部分工作,而不是cv2.mean,只需做以下事情,顺便说一下,composite = (foreground + background) 不能正常工作

rayon

您将得到:

Habitat's Slack