opencv python人脸变形完整代码
时间: 2023-07-09 13:31:04 浏览: 177
以下是利用OpenCV Python实现人脸变形的完整代码:
```
import cv2
import dlib
import numpy as np
# 加载面部标志检测器和预测器
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
# 读取输入图像
image = cv2.imread("input.jpg")
# 转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 检测脸部
faces = detector(gray)
# 循环遍历每个检测到的脸部
for face in faces:
# 获取面部标志
landmarks = predictor(gray, face)
# 将面部标志转换为NumPy数组
landmarks = np.array([[p.x, p.y] for p in landmarks.parts()])
# 选取左眉毛、右眉毛、鼻子、嘴巴和下巴的点
left_brow = landmarks[17:22]
right_brow = landmarks[22:27]
nose = landmarks[27:31]
mouth = landmarks[48:60]
chin = landmarks[6:11]
# 计算左眉毛、右眉毛、鼻子、嘴巴和下巴的中心点
left_brow_center = np.mean(left_brow, axis=0).astype(int)
right_brow_center = np.mean(right_brow, axis=0).astype(int)
nose_center = np.mean(nose, axis=0).astype(int)
mouth_center = np.mean(mouth, axis=0).astype(int)
chin_center = np.mean(chin, axis=0).astype(int)
# 在中心点处绘制蓝色圆圈
cv2.circle(image, tuple(left_brow_center), 5, (255, 0, 0), -1)
cv2.circle(image, tuple(right_brow_center), 5, (255, 0, 0), -1)
cv2.circle(image, tuple(nose_center), 5, (255, 0, 0), -1)
cv2.circle(image, tuple(mouth_center), 5, (255, 0, 0), -1)
cv2.circle(image, tuple(chin_center), 5, (255, 0, 0), -1)
# 计算左眉毛、右眉毛、鼻子、嘴巴和下巴的偏移量
left_brow_offset = (left_brow - left_brow_center).astype(float)
right_brow_offset = (right_brow - right_brow_center).astype(float)
nose_offset = (nose - nose_center).astype(float)
mouth_offset = (mouth - mouth_center).astype(float)
chin_offset = (chin - chin_center).astype(float)
# 定义目标面部形状
desired_left_brow = left_brow + left_brow_offset * 1.5
desired_right_brow = right_brow + right_brow_offset * 1.5
desired_nose = nose + nose_offset * 1.5
desired_mouth = mouth + mouth_offset * 1.5
desired_chin = chin + chin_offset * 1.5
# 合并所有目标点
desired_landmarks = np.vstack((desired_left_brow,
desired_right_brow,
desired_nose,
desired_mouth,
desired_chin))
# 计算仿射变换矩阵
transformation_matrix = cv2.estimateAffinePartial2D(
landmarks, desired_landmarks)[0]
# 将仿射变换应用于原始图像
warped_image = cv2.warpAffine(image, transformation_matrix,
(image.shape[1], image.shape[0]))
# 显示输出图像
cv2.imshow("Input", image)
cv2.imshow("Output", warped_image)
cv2.waitKey(0)
```
在代码中,我们首先加载面部标志检测器和预测器,然后读取输入图像,并将其转换为灰度图像。接着,我们使用面部标志检测器检测脸部,并循环遍历每个检测到的脸部。对于每个脸部,我们获取面部标志,并将其转换为NumPy数组。然后,我们选择左眉毛、右眉毛、鼻子、嘴巴和下巴的点,并计算它们的中心点。接着,我们在中心点处绘制蓝色圆圈,并计算左眉毛、右眉毛、鼻子、嘴巴和下巴的偏移量。然后,我们定义目标面部形状,并将所有目标点合并到一个数组中。接着,我们计算仿射变换矩阵,并将其应用于原始图像,得到变形后的图像。最后,我们显示输入和输出图像,并等待用户按下任意键退出。
阅读全文