---
title: 'Python-OpenCV进行人脸识别'
pubDate: 2018-05-18
tags:
  - 'cv'
description: 'Python-OpenCV进行人脸识别'
---

在之前的文章中，我们学习了使用数据集训练出一个识别器。本文中，我们将载入这个识别器，然后来看见怎么识别人脸。

如果[看过之前的文章](https://www.jianyujianyu.com/python-opencv-train-face-recognizer/)，你就已经准备好了一个识别器，它就在trainner文件夹和trainner.yml文件里面。

现在，我们将使用这个训练好的文件去识别人脸了。

## 导入

```
import cv2
import numpy as np
```

## 加载识别器

接下来，我们用OpenCV库以及我们训练好的数据（yml文件）创建一个识别器对象：

```
recognizer = cv2.face.LBPHFaceRecognizer_create()
# recognizer = cv2.createLBPHFaceRecognizer() # in OpenCV 2
recognizer.read('trainner/trainner.yml')
# recognizer.load('trainner/trainner.yml') # in OpenCV 2
```

然后用之前准备好的xml创建一个分类器：

```
cascade_path = "haarcascade_frontalface_default.xml"
face_cascade = cv2.CascadeClassifier(cascade_path)
```

获取到摄像头的控制对象：

```
cam = cv2.VideoCapture(0)
```

加载一个字体，用于在识别后，在图片上标注出识别对象的名字：

```
# font = cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 1, 1)
font = cv2.FONT_HERSHEY_SIMPLEX
```

## 识别程序的主循环

在程序的主循环中，我们需要做的是：

- 从摄像头中获取图像
- 将图像转换为灰度图片
- 在图片中检测人脸
- 用识别器识别该人的id
- 将识别出人脸的id或名称用矩形在图片中标出来

```
while True:
    ret, im = cam.read()
    gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.2, 5)
    for (x, y, w, h) in faces:
        cv2.rectangle(im, (x - 50, y - 50), (x + w + 50, y + h + 50), (225, 0, 0), 2)
        img_id, conf = recognizer.predict(gray[y:y + h, x:x + w])
        # cv2.cv.PutText(cv2.cv.fromarray(im), str(Id), (x, y + h), font, 255)
        cv2.putText(im, str(img_id), (x, y + h), font, 0.55, (0, 255, 0), 1)
    cv2.imshow('im', im)
    if cv2.waitKey(10) & 0xFF == ord('q'):
        break
```

`recognizer.predict`为预测函数，`putText`则是在图片上添加文字

## 更进一步

由于可能识别不出来，或者存在未知的人脸。而且，如果只用id1，id2就会大大地降低了程序的体验。因此，我们可以把id换成名字，把未知的脸标为未知。

我们把程序改成：

```
        img_id, conf = recognizer.predict(gray[y:y + h, x:x + w])
        if conf > 50:
            if img_id == 1:
                img_id = 'jianyujianyu'
            elif img_id == 2:
                img_id = 'ghost'
        else:
            img_id = "Unknown"
        # cv2.cv.PutText(cv2.cv.fromarray(im), str(Id), (x, y + h), font, 255)
        cv2.putText(im, str(img_id), (x, y + h), font, 0.55, (0, 255, 0), 1)
```

## 释放资源

记得释放资源

```
cam.release()
cv2.destroyAllWindows()
```

## 测试

然后在测试阶段，这个人工智障完美地识别不出我。

![](https://source.mkshell.com/15266221700753.jpg)

我觉得是素材不够丰富，我回头改改。。。

## 完整代码

现在的目录：

![](https://source.mkshell.com/15266224463023.jpg)

```
import cv2
import numpy as np

recognizer = cv2.face.LBPHFaceRecognizer_create()
# recognizer = cv2.createLBPHFaceRecognizer() # in OpenCV 2
recognizer.read('trainner/trainner.yml')
# recognizer.load('trainner/trainner.yml') # in OpenCV 2

cascade_path = "haarcascade_frontalface_default.xml"
face_cascade = cv2.CascadeClassifier(cascade_path)
cam = cv2.VideoCapture(0)
# font = cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 1, 1) # in OpenCV 2
font = cv2.FONT_HERSHEY_SIMPLEX

while True:
    ret, im = cam.read()
    gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.2, 5)
    for (x, y, w, h) in faces:
        cv2.rectangle(im, (x - 50, y - 50), (x + w + 50, y + h + 50), (225, 0, 0), 2)
        img_id, conf = recognizer.predict(gray[y:y + h, x:x + w])
        if conf > 50:
            if img_id == 1:
                img_id = 'jianyujianyu'
            elif img_id == 2:
                img_id = 'ghost'
        else:
            img_id = "Unknown"
        # cv2.cv.PutText(cv2.cv.fromarray(im), str(Id), (x, y + h), font, 255)
        cv2.putText(im, str(img_id), (x, y + h), font, 0.55, (0, 255, 0), 1)
    cv2.imshow('im', im)
    if cv2.waitKey(10) & 0xFF == ord('q'):
        break

cam.release()
cv2.destroyAllWindows()
```

_先这样吧_

[原文](https://thecodacus.com/face-recognition-loading-recognizer/)，若有错误之处请指出，更多地关注[煎鱼](http://www.jianyujianyu.com)。
