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'
Python+opencv人脸识别
最新推荐文章于 2021-11-27 13:45:19 发布