python根据检测到的人脸添加圣诞帽图片
时间: 2023-06-12 09:03:46 浏览: 92
要实现这个功能,可以使用Python的OpenCV和Pillow库。首先,需要检测人脸并标记出人脸位置,然后将圣诞帽图片按照人脸位置进行缩放和旋转,并将其贴在原始图像上。
下面是一个示例代码,可以实现上述功能:
```python
import cv2
from PIL import Image
# 加载人脸检测器
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# 加载圣诞帽图片
hat_img = Image.open('santa_hat.png')
# 加载原始图片
img = cv2.imread('test.jpg')
# 将原始图片转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 检测人脸
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
# 遍历每个检测到的人脸
for (x, y, w, h) in faces:
# 将圣诞帽图片缩放和旋转,使其适合当前人脸大小和角度
hat_width = int(1.5 * w)
hat_height = int(hat_width * hat_img.height / hat_img.width)
hat_img_resized = hat_img.resize((hat_width, hat_height))
hat_img_rotated = hat_img_resized.rotate(30)
# 将圣诞帽图片贴在原始图像上
hat_img_np = cv2.cvtColor(np.array(hat_img_rotated), cv2.COLOR_RGB2BGR)
x_offset = int(x - 0.25 * w)
y_offset = int(y - 0.75 * h)
img[y_offset:y_offset+hat_img_np.shape[0], x_offset:x_offset+hat_img_np.shape[1]] = hat_img_np
# 显示结果
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在运行代码之前,需要将代码中的`haarcascade_frontalface_default.xml`和`santa_hat.png`替换为自己的文件路径。另外,还需要安装`opencv-python`和`Pillow`库。
运行代码后,将在原始图片上添加圣诞帽,并显示结果图像。