首页 > 解决方案 > 试图模糊面部(python)

问题描述

我试图通过使用以下脚本来模糊面部,但最终会模糊整个图像。有关如何更改脚本以使其仅模糊面孔的任何建议?

import numpy as np
import cv2

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

img = cv2.imread('beatles.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Detecting faces
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
    img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = img[y:y+h, x:x+w]


# To show the detected faces
cv2.imshow('img',img)
cv2.waitKey(5000)
cv2.destroyAllWindows()

k = np.array(([1/9, 1/9, 1/9], [1/9, 1/9, 1/9], [1/9, 1/9, 1/9]), np.float32)

# Blurring of just the faces in a picture 
skaldetlykkes = cv2.filter2D(img, -1, k)
cv2.imshow("Ladetskje", skaldetlykkes)
cv2.waitKey (5000)
cv2.destroyAllWindows() 

标签: pythonanaconda

解决方案


此代码示例

import cv2

# Load the cascade
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# Read the input image
img = cv2.imread('test.jpg')

# Convert into grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Detect faces
faces = face_cascade.detectMultiScale(gray, 1.1, 4)

# Draw rectangle around the faces
for (x, y, w, h) in faces:
    cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)

# Display the output
cv2.imshow('img', img)
cv2.waitKey()

从人脸检测应该计算你想要模糊的矩形区域。

然后你只需要在该区域上应用一个平均函数:)(模糊 = 窗口平均值)


推荐阅读