写一个python opencv输入人脸三个数据点进行旋转对齐的程序
时间: 2023-05-27 20:06:38 浏览: 62
以下是一个基于Python和OpenCV的输入人脸三个数据点进行旋转对齐的程序:
```python
import cv2
import numpy as np
# 定义函数,输入人脸图像和三个关键点坐标,输出旋转后的图像
def align_face(img, left_eye, right_eye, nose_tip):
# 计算两个眼睛的中心点坐标,并计算眼睛之间的距离
eye_center = ((left_eye[0] + right_eye[0]) // 2, (left_eye[1] + right_eye[1]) // 2)
eye_distance = np.sqrt((right_eye[0] - left_eye[0])**2 + (right_eye[1] - left_eye[1])**2)
# 计算旋转角度
angle = np.degrees(np.arctan2(right_eye[1] - left_eye[1], right_eye[0] - left_eye[0]))
# 计算仿射变换矩阵
M = cv2.getRotationMatrix2D(eye_center, angle, scale=1)
# 将关键点坐标转换为二维矩阵
points = np.array([left_eye, right_eye, nose_tip])
points = np.concatenate((points, np.ones((3, 1))), axis=1)
points = points.dot(M.T)
# 对图像进行仿射变换
aligned_img = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]), flags=cv2.INTER_CUBIC)
return aligned_img, points[:, :2]
# 读取人脸图像和关键点坐标
img = cv2.imread('face.jpg')
left_eye = (100, 200)
right_eye = (300, 200)
nose_tip = (200, 300)
# 进行旋转对齐
aligned_img, aligned_points = align_face(img, left_eye, right_eye, nose_tip)
# 在图像上绘制关键点
cv2.circle(img, left_eye, 2, (0, 255, 0), 2)
cv2.circle(img, right_eye, 2, (0, 255, 0), 2)
cv2.circle(img, nose_tip, 2, (0, 255, 0), 2)
cv2.imshow('Original Image', img)
# 在旋转后的图像上绘制关键点
cv2.circle(aligned_img, (int(aligned_points[0][0]), int(aligned_points[0][1])), 2, (0, 255, 0), 2)
cv2.circle(aligned_img, (int(aligned_points[1][0]), int(aligned_points[1][1])), 2, (0, 255, 0), 2)
cv2.circle(aligned_img, (int(aligned_points[2][0]), int(aligned_points[2][1])), 2, (0, 255, 0), 2)
cv2.imshow('Aligned Image', aligned_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这个程序可以读取一张人脸图像和三个关键点坐标,然后使用这些坐标计算旋转角度,并对图像进行旋转对齐。最后,程序会在原始图像和旋转后的图像上绘制关键点,以便比较两者之间的差异。