11
运行上面的代码可以看到这样的结果:
旋转
需要旋转,是因为我们需要把两张图片上的人脸进行对齐操作。旋转的变换操作矩阵是:
⎡⎣cos(θ)sin(θ)0−sin(θ)cos(θ)0001⎤⎦ \left[\begin{matrix}cos(\theta) & -sin(\theta) & 0 \sin(\theta) & cos(\theta) & 0 \0 & 0 & 1\end{matrix} \right]
⎣
⎡
cos(θ)
sin(θ)
0
−sin(θ)
cos(θ)
0
0
0
1
⎦
⎤
如果我们想要旋转30度,可以使用一下代码:
img = cv2.imread(“./imgs/2.jpg”)
theta = math.radians(-30)
M = np.float32(
[
[np.cos(theta), -np.sin(theta), 0],
[np.sin(theta), np.cos(theta), 0]
]
)
dst = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))
cv2.imshow(“”, dst)
cv2.waitKey()
1
2
3
4
5
6
7
8
9
10
11
12
13
运行效果如下:
观察结果可能发现了,这次旋转的中心是在原点,如果我们想以任意点为旋转中心怎么办? opencv提供了一个函数:
getRotationMatrix2D(center, angle, scale)
1
center: 指定旋转的中心
angle: 旋转角度
scale: 缩放因子
这个函数还顺手解决了我们上面需要的缩放操作。可以比较下面代码和上面的效果:
img = cv2.imread(“./imgs/2.jpg”)
M = cv2.getRotationMatrix2D((img.shape[1], img.shape[0]), 30, 1)
dst = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))
cv2.imshow(“”, dst)
cv2.waitKey()
1
2
3
4
5
6
7
最强变脸术第一次实现
仿射变换版本其实就是利用了以上三种变换方式的组合,首先先定义一个函数入口。
def compose_img(name, frames_per_transformer, wait_frames, *imgs):
pass
1
2
参数1:生成视频的文件名
参数2:每两张图像之前的变换(称之为1次迭代)需要多少帧
参数3:每个迭代后写入多少帧静态图,也就是每次迭代完成后图片保持多少帧不变
参数4:参与生成视频的图片集合
除了这个函数外,我们还需要几个辅助函数。
def to_video(name, width, height):
fps = 10
video_writer = cv2.VideoWriter(name, cv2.VideoWriter_fourcc(‘I’, ‘4’, ‘2’, ‘0’), fps, (width, height))
return video_writer
def get_equation(x0, y0, x1, y1, pow_arg=1):
k = (y1 - y0) / (pow(x1, pow_arg) - pow(x0, pow_arg))
b = y0 - k * pow(x0, pow_arg)
def f(x):
return k * pow(x, pow_arg) + b
return f
def get_rotate_theta(from_landmarks, to_landmarks):
from_left_eye = from_landmarks[36]
from_right_eye = from_landmarks[45]
to_left_eye = to_landmarks[36]
to_right_eye = to_landmarks[45]
from_angle = math.atan2(from_right_eye[1] - from_left_eye[1], from_right_eye[0] - from_left_eye[0])
to_angle = math.atan2(to_right_eye[1] - to_left_eye[1], to_right_eye[0] - to_left_eye[0])
from_theta = -from_angle * (180 / math.pi)
to_theta = -to_angle * (180 / math.pi)
return to_theta - from_theta
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18<