发布于 2014-10-14 23:18:45 | 263 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Python教程,程序狗速度看过来!

Python编程语言

Python 是一种面向对象、解释型计算机程序设计语言,由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年。Python语法简洁而清晰,具有丰富和强大的类库。它常被昵称为胶水语言,它能够把用其他语言制作的各种模块(尤其是C/C++)很轻松地联结在一起。


本文为大家讲解了python中使用OpenCV如何进行人脸检测的方法,需要的朋友可以参考下

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

 



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务