CPP操作小案例

人脸识别小案例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

CascadeClassifier face_detect = CascadeClassifier("../assets/haarcascade_frontalface_default.xml");
CascadeClassifier eye_detect = CascadeClassifier("../assets/haarcascade_eye.xml");


int main(){
    Mat img = imread("../assets/lena.jpg",IMREAD_COLOR);

    vector<Rect> faces;
    face_detect.detectMultiScale(img,faces,1.3);

    for (int i = 0; i < faces.size(); ++i) {
        // 绘制人脸
        Rect face = faces.at(i);
        rectangle(img,face,Scalar(255,255,0),2);

        // 从图像上截取出人脸
        Mat faceImg = img(face);

        // 查找眼睛,并且绘制眼睛
        vector<Rect> eyes;
        eye_detect.detectMultiScale(faceImg,eyes,1.3);
        for (int j = 0; j < eyes.size(); ++j) {
            Rect eye = eyes.at(j);
            rectangle(faceImg,eye,Scalar(0,255,255),2);
        }
    }
    imshow("img",img);

    waitKey(0);
    destroyAllWindows();
    return 0;
}

人脸替换

示例代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

CascadeClassifier face_detect = CascadeClassifier("../assets/haarcascade_frontalface_default.xml");
CascadeClassifier eye_detect = CascadeClassifier("../assets/haarcascade_eye.xml");


int main(){
    Mat img = imread("../assets/lena.jpg",IMREAD_COLOR);
    imshow("img",img);

    vector<Rect> faces;
    face_detect.detectMultiScale(img,faces,1.3);


    for (int i = 0; i < faces.size(); ++i) {
        // 找到人脸位置
        Rect face = faces.at(i);

        // 创建一个和原图一样大小的蒙板
        Mat mask = Mat::zeros(img.size(),CV_8UC1);
        // 设置感兴趣的区域为全白色
        mask(face).setTo(255);
        imshow("mask",mask);

        // 使用蒙板,从原图中抠出感兴趣的图像
        Mat copyFace;
        img.copyTo(copyFace,mask);
        imshow("copyFace",copyFace);

        // 对拷贝出来的人脸进行Canny边缘提取
        Mat cannyImg;
        Canny(copyFace,cannyImg,100,200);
        imshow("canny",cannyImg);

        // 将原图,人脸位置留空
        img(face) = Vec3b(0,0,0);
        imshow("img kong",img);

        // 将单通道的canny图转成BGR三通道的图像
        Mat cannyImg3;
        cvtColor(cannyImg,cannyImg3,COLOR_GRAY2BGR);

        // 将留空的原图和3通道的Canny图加在一起
        Mat dst;
        add(cannyImg3,img,dst);
        imshow("dst",dst);

    }

    waitKey(0);
    destroyAllWindows();
    return 0;
}