Face Detection in Static Images with Python

來源:互聯網
上載者:User

   OpenCV的臉部偵測功能在一般場合還是不錯的。而ubuntu正好提供了python-opencv這個包,用它可以方便地實現臉部偵測的代碼。

寫代碼之前應該先安裝python-opencv:

$ sudo apt-get install python-opencv
我測試電腦上提示依賴其他檔案,我裝了libcurl3,然後重新上面的步驟,就可以了。代碼如下:
#!/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(
'/home/username/face/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')

 

參考:

1)Face Detection in Static Images with Python

2)python+OpenCV進行臉部偵測 

 

指令碼中用到的檔案:http://tutorial-haartraining.googlecode.com/svn/trunk/data/haarcascades/haarcascade_frontalface_default.xml

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.