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

yipeiwu_com6年前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')

相关文章

Django models.py应用实现过程详解

Django models.py应用实现过程详解

编写 models.py 文件 from django.db import models # Create your models here. class User_info(mod...

Python 基于wxpy库实现微信添加好友功能(简洁)

Python 基于wxpy库实现微信添加好友功能(简洁)

Github:https://github.com/Lyo-hub/wxpy_AddFriend 本程序为基于wxpy库实现的。 1.打开cmd导入一下库。 2.修改库文件中ad...

Python获取暗黑破坏神3战网前1000命位玩家的英雄技能统计

Python获取暗黑破坏神3战网前1000命位玩家的英雄技能统计

说实在的个人对游戏并没有多大的兴趣,但唯独对暴雪的Diablo系列很有感情,去年年初开始玩Diablo3,断断续续,感觉最麻烦的是选择技能,每次版本更新可能都有更优的build,这对于我...

pandas 实现字典转换成DataFrame的方法

把dictd = {'A':0}转换成DataFrame, 首先,DataFrame的语法格式应为: import pandas as pd df = pd.DataFrame({'...

Python将图片批量从png格式转换至WebP格式

Python将图片批量从png格式转换至WebP格式

实现效果 将位于/img目录下的1000张.png图片,转换成.webp格式,并存放于img_webp文件夹内。 源图片目录 目标图片目录 关于批量生成1000张图片,可以参考这篇文...