OpenCV的全称是Open Source Computer Vision Library,是一个跨平台的计算机视觉库。OpenCV是由英特尔公司发起并参与开发,以BSD许可证授权发行,可以在商业和研究领域中免费使用。OpenCV可用于开发实时的图像处理、计算机视觉以及模式识别程序。

目前我们比较感兴趣的是它在人脸识别上的应用。

在ubuntu上的安装:

首先确保电脑上已经安装了GTK+ 2.x和Cmake。

sudo apt-get install libgtk2.0-dev pkg-config  cmake

接下来从网上下载OpenCV的源代码。我下载的是OpenCV-2.4.4a.tar.bz2。

解压进入文件夹。

tar -jxvf OpenCV-2.4.4a.tar.bz2  

cd OpenCV-2.4.4

建立目录release,我们的安装将在这个目录下进行。

mkdir release  

cd release  

进入目录后,执行下面命令(注意,这是一条完整的命令,包括最后的..)进行配置,需要注意的是安装目录这一项。

cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/home/OpenCV-2.4.4 -D BUILD_PYTHON_SUPPORT=ON ..

执行完毕后,release目录下出现Makefile等文件。

接下来make编译,然后安装

make
sudo make install

安装完毕后

cd /home/OpenCV-2.4.4
leon@leon-Founder-PC:/home/OpenCV-2.4.4$ ls
bin  include  lib  share

至此安装完成,接下来修改环境变量。

sudo gedit /etc/bash.bashrc

在文件中添加下面两项:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/OpenCV-2.4.4/lib/
export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/home/OpenCV-2.4.4/lib/pkgconfig

测试:

在OpenCV的源码包里有Samples文件夹,里面有各个平台的例程。

leon@leon-Founder-PC:~/cam/opencv-2.4.4/samples$ ls

android  c  CMakeLists.txt  cpp  gpu  java  MacOSX  ocl  python  python2

我们使用最熟悉的C。进入该文件夹,下面有非常多的文件,我们编译例程只需要一个文件:build_all.sh。

leon@leon-Founder-PC:~/cam/opencv-2.4.4/samples/c$ ls
...
build_all.sh
leon@leon-Founder-PC:~/cam/opencv-2.4.4/samples/c$ ./build_all.sh

等待编译完成后,我们就可以测试了,选择现有的人脸检测例程。

leon@leon-Founder-PC:~/cam/samples/c$ ./facedetect --cascade="/home/OpenCV-2.4.4/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml" --scale=1.9 ~/Pictures/1.png

程序运行,这个程序的解释还是很清楚的:

This program demonstrates the cascade recognizer. Now you can use Haar or LBP features.This classifier can recognize many kinds of rigid objects, once the appropriate classifier is trained.
It's most known use is for faces.
Usage:
./facedetect [--cascade=<cascade_path> this is the primary trained classifier such as frontal face]
   [--nested-cascade[=nested_cascade_path this an optional secondary classifier such as eyes]]
   [--scale=<p_w_picpath scale greater or equal to 1, try 1.3 for example>]
   [--try-flip]
   [filename|camera_index]
see facedetect.cmd for one call:
./facedetect --cascade="../../data/haarcascades/haarcascade_frontalface_alt.xml" --nested-cascade="../../data/haarcascades/haarcascade_eye.xml" --scale=1.3
During execution:
Hit any key to quit.
Using OpenCV version 2.4.4
Processing 1 --cascade=/home/OpenCV-2.4.4/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml
  from which we have cascadeName= /home/OpenCV-2.4.4/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml
Processing 2 --scale=1.9
 from which we read scale = 1.9
Processing 3 /home/leon/Pictures/1.jpg
In p_w_picpath read
detection time = 198.629 ms

程序执行效果:

090837115.jpg

在接下来,对其他几张照片测试,发现这个例程只能检测到清晰的正面人脸,而且会出现漏检,误检。