python中使用OpenCV進行人臉檢測的例子
OpenCV的人臉檢測功能在一般場合還是不錯的。而ubuntu正好提供了python-opencv這個包,用它可以方便地實現(xiàn)人臉檢測的代碼。
寫代碼之前應(yīng)該先安裝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')
- 人臉檢測實戰(zhàn)終極之OpenCV+Python實現(xiàn)人臉對齊
- python基于Opencv實現(xiàn)人臉口罩檢測
- Python OpenCV利用筆記本攝像頭實現(xiàn)人臉檢測
- python opencv人臉檢測提取及保存方法
- python版opencv攝像頭人臉實時檢測方法
- Python3.6.0+opencv3.3.0人臉檢測示例
- Python+OpenCV人臉檢測原理及示例詳解
- python利用OpenCV2實現(xiàn)人臉檢測
- python結(jié)合opencv實現(xiàn)人臉檢測與跟蹤
- 使用 Python 和 OpenCV 實現(xiàn)攝像頭人臉檢測并截圖功能
相關(guān)文章
Python利用shutil模塊實現(xiàn)文件的裁剪與壓縮
shutil可以簡單地理解為sh+util ,shell工具的意思。shutil模塊是對os模塊的補充,主要針對文件的拷貝、刪除、移動、壓縮和解壓操作。本文將利用這一模塊實現(xiàn)文件的裁剪、壓縮與解壓縮,需要的可以參考一下2022-05-05Python字符串中的單詞反轉(zhuǎn)的實現(xiàn)示例
在Python中,要將字符串中的單詞進行反轉(zhuǎn),本文主要介紹了Python字符串中的單詞反轉(zhuǎn)的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-04-04Python時間管理黑科技之datetime函數(shù)詳解
在Python中,datetime模塊是處理日期和時間的標(biāo)準(zhǔn)庫,它提供了一系列功能強大的函數(shù)和類,用于處理日期、時間、時間間隔等,本文將深入探討datetime模塊的使用方法,感興趣的可以了解下2023-08-08