国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python中使用OpenCV進行人臉檢測的例子

2020-02-23 05:20:23
字體:
來源:轉載
供稿:網友

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 岫岩| 出国| 若尔盖县| 晋宁县| 绵阳市| 梓潼县| 民县| 普陀区| 唐山市| 丰宁| 肥西县| 梨树县| 随州市| 平塘县| 固始县| 贵州省| 历史| 平谷区| 黑龙江省| 成安县| 瑞丽市| 上林县| 南溪县| 新丰县| 齐齐哈尔市| 静乐县| 泸州市| 东阳市| 灵川县| 普兰县| 和静县| 平定县| 榆社县| 霍林郭勒市| 毕节市| 永寿县| 达孜县| 彰武县| 策勒县| 夹江县| 五河县|