dlib 19.24 c++ 人脸矫正的例子
时间: 2023-07-23 22:06:41 浏览: 54
以下是使用dlib 19.24 c++进行人脸矫正的示例代码:
```c++
#include <dlib/image_processing/frontal_face_detector.h>
#include <dlib/image_processing.h>
#include <dlib/gui_widgets.h>
#include <dlib/image_io.h>
using namespace dlib;
int main()
{
try
{
// Load the face detection model.
frontal_face_detector detector = get_frontal_face_detector();
shape_predictor sp;
deserialize("shape_predictor_68_face_landmarks.dat") >> sp;
// Load the image.
array2d<rgb_pixel> img;
load_image(img, "test.jpg");
// Detect faces.
std::vector<rectangle> dets = detector(img);
// Find the pose of each face.
std::vector<full_object_detection> shapes;
for (unsigned long i = 0; i < dets.size(); ++i)
shapes.push_back(sp(img, dets[i]));
// Draw the detected faces.
image_window win;
win.set_image(img);
win.add_overlay(dets, rgb_pixel(255, 0, 0));
// Draw the facial landmarks on each face.
for (unsigned long i = 0; i < shapes.size(); ++i)
win.add_overlay(render_face_detections(shapes[i]));
// Get the affine transform for each face and apply it to the image.
for (unsigned long i = 0; i < shapes.size(); ++i)
{
rectangle rect = shapes[i].get_rect();
full_object_detection shape = shapes[i];
matrix<double, 3, 3> trans = get_affine_transform(shape);
array2d<rgb_pixel> face_chip;
extract_image_chip(img, get_face_chip_details(shape,150,0.25), face_chip);
transform_image(face_chip, face_chip, interpolate_bilinear());
win.add_overlay(image_window::overlay_rect(rect, rgb_pixel(255, 0, 0), "face"));
win.add_overlay(image_window::overlay_rect(get_face_chip_details(shape,150,0.25), rgb_pixel(0, 255, 0), "chip"));
win.add_overlay(render_face_detections(shapes[i], rgb_pixel(0, 255, 0)));
save_png(face_chip, "face_chip_" + std::to_string(i+1) + ".png");
}
// Wait for the user to close the window.
win.wait_until_closed();
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
}
```
此示例代码使用dlib的面部检测器和形状预测器来检测图像中的面部,并使用面部的关键点来获取每个面部的仿射变换矩阵。然后,它将这些仿射变换应用于原始图像中的面部,以便进行矫正。最后,它将矫正后的面部保存为图像文件。
注意:在使用此示例代码之前,您需要下载dlib的面部检测器和形状预测器,并将其保存在与示例代码相同的目录中。您还需要将示例代码中的“test.jpg”更改为您要矫正的实际图像文件名。