python中使用OpenCV进行人脸检测的例子

yipeiwu_com5年前Python基础

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 <image_file>

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')

相关文章

python计算两个地址之间的距离方法

我们调用高德地图的API来计算经纬度 #计算地址经纬度 import requests def geocode(address): parameters = {'address':...

python实现在cmd窗口显示彩色文字

python实现在cmd窗口显示彩色文字

新手小白,一直在为cmd窗口的暗白色文字感到苦恼,在网上找了许多方法(也就那两种吐舌头),现在稍微整理了一下,便于使用。 效果图: import ctypes STD_INPU...

Python实现建立SSH连接的方法

本文实例讲述了Python实现建立SSH连接的方法。分享给大家供大家参考。具体实现方法如下: 我需要实现一个Windows下远程连接到SSH服务器执行命令的功能,所以就在网上找资料。我的...

使用Python中的tkinter模块作图的方法

使用Python中的tkinter模块作图的方法

python简述: Python是一种解释型、面向对象、动态数据类型的高级程序设计语言。自从20世纪90年代初Python语言诞生至今,它逐渐被广泛应用于处理系统管理任务和Web编程。P...

Python 取numpy数组的某几行某几列方法

Python 取numpy数组的某几行某几列方法

直接分析,如原矩阵如下(1):   (1) 我们要截取的矩阵(取其一三行,和三四列数据构成矩阵)为如下(2):   (2) 错误分析: 取 C 的1 3行...