python+OpenCV进行人脸检测

idv2 2012-01-24 13:29:43 累计浏览 4,943 次

    OpenCV的人脸检测功能在一般场合还是不错的。而ubuntu正好提供了python-opencv这个包,用它可以方便地实现人脸检测的代码。

    写代码之前应该先安装python-opencv:

$ sudo apt-get install python-opencv

    具体原理就不多说了,可以参考一下这篇文章。直接上源代码。

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# face_detect.py

# Face Detection using OpenCV. Based on sample code from:
# http://python.pastebin.com/m76db1d6b

# Usage: python face_detect.py 

import sys, os
from opencv.cv import *
from opencv.highgui import *
from PIL import Image, ImageDraw
from math import sqrt

def detectObjects(image):
    """Converts an image to grayscale and prints the locations of any faces found"""
    grayscale = cvCreateImage(cvSize(image.width, image.height), 8, 1)
    cvCvtColor(image, grayscale, CV_BGR2GRAY)

    storage = cvCreateMemStorage(0)
    cvClearMemStorage(storage)
    cvEqualizeHist(grayscale, grayscale)

    cascade = cvLoadHaarClassifierCascade(
        \'/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml\',
        cvSize(1,1))
    faces = cvHaarDetectObjects(grayscale, cascade, storage, 1.1, 2,
        CV_HAAR_DO_CANNY_PRUNING, cvSize(20,20))

    result = []
    for f in faces:
        result.append((f.x, f.y, f.x+f.width, f.y+f.height))

    return result

def grayscale(r, g, b):
    return int(r * .3 + g * .59 + b * .11)

def process(infile, outfile):

    image = cvLoadImage(infile);
    if image:
        faces = detectObjects(image)

    im = Image.open(infile)

    if faces:
        draw = ImageDraw.Draw(im)
        for f in faces:
            draw.rectangle(f, outline=(255, 0, 255))

        im.save(outfile, "JPEG", quality=100)
    else:
        print "Error: cannot detect faces on %s" % infile

if __name__ == "__main__":
    process(\'input.jpg\', \'output.jpg\')

    检测结果:

face_detect_output.jpg

同分类推荐文章

  1. 科技爱好者周刊(第 416 期):编程已经面目全非 (2026-11-14 04:10:02)
  2. AI Native 实践续篇:迈向 Stage 8 (2026-11-14 02:40:02)
  3. Is Your Organization Messing Up AI Adoption? (2026-11-14 00:40:02)

查看更多 AI 文章 →

建议继续学习

  1. 用Hyer来进行网站的抓取 (累计阅读 158,836)
  2. 配置Nginx+uwsgi更方便地部署python应用 (累计阅读 109,257)
  3. 程序员技术练级攻略 (累计阅读 36,062)
  4. python实现自动登录discuz论坛 (累计阅读 33,280)
  5. python编程细节──遍历dict的两种方法比较 (累计阅读 21,007)
  6. 每个程序员都应该学习使用Python或Ruby (累计阅读 18,310)
  7. Chrome和goagent的配置方法,你懂的 (累计阅读 17,492)
  8. 30分钟3300%性能提升――python+memcached网页优化小记 (累计阅读 14,112)
  9. 使用python爬虫抓站的一些技巧总结:进阶篇 (累计阅读 13,776)
  10. 我的PHP,Python和Ruby之路 (累计阅读 13,719)