正如我在第 3 节中看到的那样,最简单的方法是:
-
在图像中查找人脸:
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags = cv2.cv.CV_HAAR_SCALE_IMAGE
)
-
为每个面计算中点:
for (x, y, w, h) in faces:
mid_x = x + int(w/2)
mid_y = y + int(h/2)
-
仿射变换图像以使您已经计算的蓝点居中:
height, width = img.shape
x_dot = ...
y_dot = ...
dx_dot = int(width/2) - x_dot
dy_dot = int(height/2) - y_dot
M = np.float32([[1,0,dx_dot],[0,1,dy_dot]])
dst = cv2.warpAffine(img,M,(cols,rows))
希望对您有所帮助。
编辑:
关于第 4 节:
为了拉伸(调整大小)图像,您所要做的就是执行仿射变换。为了找到变换矩阵,我们需要输入图像中的三个点及其在输出图像中的对应位置。
p_1 = [eyes_x, eye_y]
p_2 = [int(width/2),int(height/2)] # default: center of the image
p_3 = [mouth_x, mouth_y]
target_p_1 = [eyes_x, int(eye_y * 0.45)]
target_p_2 = [int(width/2),int(height/2)] # don't want to change
target_p_3 = [mouth_x, int(mouth_y * 0.75)]
pts1 = np.float32([p_1,p_2,p_3])
pts2 = np.float32([target_p_1,target_p_2,target_p_3])
M = cv2.getAffineTransform(pts1,pts2)
output = cv2.warpAffine(image,M,(height,width))
清除:
-
eye_x / eye_y 是眼球中心的位置。
- 同样适用于
mouth_x / mouth_y,嘴巴中心。
-
target_p_1/2/3 是目标点。
编辑 2:
我看到你遇到了麻烦,希望这次我的建议对你有用:
我可以想到另一种方法。您可以通过指向 4 个点对图像进行某种“裁剪”,让我们将它们定义为包裹面部的 4 个点,并根据它们的新位置更改图像透视:
up_left = [x,y]
up_right = [...]
down_left = [...]
down_right = [...]
pts1 = np.float32([up_left,up_right,down_left,down_right])
pts2 = np.float32([[0,0],[300,0],[0,300],[300,300]])
M = cv2.getPerspectiveTransform(pts1,pts2)
dst = cv2.warpPerspective(img,M,(300,300))
所以您所要做的就是定义这 4 点。我的建议是计算脸部周围的轮廓(你已经做过),然后在坐标中添加 delta_x 和 delta_y(或减去)。