0基础用OpenCV做人脸识别示例

最近摸索了一下怎么做人脸识别,大家都说用OpenCV,懂python就可以写。好奇心驱使,尝试了一下,出奇地容易(里面的数学知识,不是一下就能弄懂的,但不妨碍做demo)。通常整理网上的一些样例,自己再调整一下程序框架,基本可以整个人脸识别的小玩具来在Mac Air上把玩。目前,可以实现:

  • 调用Mac Book Air的摄像头的画面
  • 当发现有一个或多个人脸出现在摄像头区域,加入线框标记并在console上打印人脸在屏幕的坐标
  • 当检测到有人脸出现于屏幕并且屏幕有较大变化时,截取屏幕图片
  • 在程序退出时,把截取到的屏幕图片人脸抠出来保存

以下是安装和运行过程的简要记录,程序源码记录在GitHub - opencv-sample上,欢迎Fork或PR及提出宝贵意见。

Environment

  • Mac Book Air
  • Python3
  • OpenCV2

Folder Structure

1
2
3
4
5
6
├── cv-camera.py       #用opencv动态识别mac摄像头的数据,并在适当时候截图
├── cv-image.py #用opencv识别一个图片的人脸
├── data #从opencv上复制过来的特征数数
├── images
│   └── sample.jpeg #cv-image.py 的默认识别样图片
└── result #ca-camera.py 的输出目录

Installations (for Mac only)

  • Ensure brew, xcode installed and update
  • Install the opencv by brew (最好翻墙后搞,会顺利点。)

    1
    2
    3
    4
    5
    $ brew install opencv
    Updating Homebrew...
    ...
    ...
    ...
  • Verification

    1
    2
    3
    4
    5
    $ python3
    Python 3.6.4 (default, Jan 6 2018, 11:51:15)
    [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import cv2

    按理Brew应该会给python2和python3都安装opencv的库,但不知为什么我的mac安装后,只有python3管用。有经验的同学,麻烦指导一下

  • Install the additional libs by pip

    1
    pip3 install -r requirements.txt

Trail run

  • cv-image.py - detect the face from a image and draw the result in a new python window

    1
    2
    3
    4
    python3 cv-image.py

    # or you can specify a image you want
    python3 cv-image.py --image images/sample.jpeg
    • you can press any key to exits
    • sample result: cv-image
  • cv-camera.py

    1
    2
    3
    python3 cv-camera.py

    # this script will load the source from camera and detect the face real time
    • press ‘c’ to capture a image
    • press ‘q’ to exits
    • the program will capture max. 50 screen in the result folder, when it got new face detected or ‘c’ key press
    • when the program exists, it will detec the face of the screen captured in result folder and save the related faces in subfolder.
    • sample result: cv-camer
0%