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

相关文章

Pytorch保存模型用于测试和用于继续训练的区别详解

保存模型 保存模型仅仅是为了测试的时候,只需要 torch.save(model.state_dict, path) path 为保存的路径 但是有时候模型及数据太多,难以一次性训...

Python实现新浪博客备份的方法

本文实例讲述了Python实现新浪博客备份的方法。分享给大家供大家参考,具体如下: Python2.7.2版本实现,推荐在IDE中运行。 # -*- coding:UTF-8 -*-...

python通过opencv实现批量剪切图片

上一篇文章中,我们介绍了python实现图片处理和特征提取详解,这里我们再来看看Python通过OpenCV实现批量剪切图片,具体如下。 做图像处理需要大批量的修改图片尺寸来做训练样本,...

使用Python的Dataframe取两列时间值相差一年的所有行方法

在使用Python处理数据时,经常需要对数据筛选。 这是在对时间筛选时,判断两列时间是否相差一年,如果是,则返回符合条件的所有列。 data原始数据: data[map(lambda...

python实现整数的二进制循环移位

python实现整数的二进制循环移位

题目:如何在python中实现整数的二进制循环移位? 概述 在python中,可以通过<<以及>>运算符实现二进制的左移位以及右移位,然而并没有实现循环移位的运算...