Python+opencv人脸识别

import cv2
from PIL import Image,ImageDraw
import os


p_width = 480
p_height = 640
# CV Configs for face detection
scaleFactor = 1.2
minNeighbors = 5
minSize = (10, 10)
# Save quality
jpg_quality = 100
# face features
cascPath = 'haarcascade_frontalface_alt.xml'

def calc_photo_xy(f):
    '''Calculate the face image location
    '''
    x1 = f[0]
    y1 = f[1]
    x2 = f[0] + f[2]
    y2 = f[1] + f[3]
    return (x1, y1, x2, y2)

# load the classifier
faceCascade = cv2.CascadeClassifier(cascPath)

def find_face(imagePath):
    '''进行面部识别并保存头像照片
    imagePath: 待识别照片存放的绝对路径
    '''
    im = Image.open(imagePath)
    path = os.path.abspath(imagePath)
    save_path = './faces'
    try:
        os.mkdir(save_path)
    except:
        pass
    imagesave = './faces/face_%s.jpg'
    # Read Image
    image = cv2.imread(imagePath)
    # Change Color
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    # Detect faces in the image
    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=scaleFactor,
        minNeighbors=minNeighbors,
        minSize=minSize,
        flags = cv2.cv.CV_HAAR_SCALE_IMAGE
    )
    
    if len(faces)<1:
        return None
    else:
        draw = ImageDraw.Draw(im)
        count = 0
        for face in faces:
            count += 1
            # Calc a Photo xy
            xy = calc_photo_xy(face)
            # Chop the photo and save            
            region = im.crop(xy)
            region_small = region.resize((p_width, p_height), Image.ANTIALIAS)
            region_small.save(imagesave % count, quality=jpg_quality)                   
        for face in faces:
            # Calc a Photo xy
            xy = calc_photo_xy(face)          
            #draw the box 
            draw.rectangle(xy, outline=(255, 0, 0))

        drow_save_path = os.path.join(save_path,"out.jpg")
        im.save(drow_save_path, "JPEG", quality=80)    
        return 'ok'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值