faceUtil.py
#!/user/bin/ env python
# -*- coding:utf-8 -*-
# Author: Chen X
import cv2
import matplotlib as plt
#默认值
#把安装opencv的目录下的默认数据xml的位置放进去
model_face ='D:\Maindocument\opencvfile\opencv\sources\data\haarcascades/haarcascade_frontalface_default.xml'
min_height_dec = 20
min_width_dec = 20
min_height_thresh = 50
min_width_thresh = 50
FACE_PAD = 50
#人脸模型
def get_model_type(model_name):
if not (model_face):
return cv2.CascadeClassifier(model_face)
return cv2.CascadeClassifier(model_face)
#人脸识别
#回脸和IMG
def detect_faces(face_model,image_name):
face_cascade = get_model_type(face_model)#加载模型
print(image_name)
img = cv2.imread(image_name)#读取图片
print(img)
min_h = int(max(img.shape[0]/min_height_dec,min_height_thresh))
min_w = int(max(img.shape[1]/min_width_dec,min_width_thresh))
if img.ndim == 3 :
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
else:
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)#转灰度
faces = face_cascade.detectMultiScale(gray,1.3,minNeighbors=5,minSize=(min_h,min_w))
result = []
for (x,y,width,height) in faces:
result.append((x,y,x+width,y+height))
draw_rect(img,x,y,width,height) #划线标记
return (result,img)
#画图
def draw_rect(img,x,y,w,h):
upper_cut = [min(img.shape[0],y+h+FACE_PAD),min(img.shape[1],x+w+FACE_PAD)]
lower_cut = [max(y-FACE_PAD,0),max(x-FACE_PAD,0)]
img = cv2.rectangle(img,(lower_cut[1],lower_cut[0]),(upper_cut[1],upper_cut[0]),
(255,0,0),2)
#截取图字图片
def sub_image(name,img,x,y,w,h):
upper_cut = [min(img.shape[0],y+h+FACE_PAD),min(img.shape[1],x+w+FACE_PAD)]
lower_cut = [max(y - FACE_PAD, 0), max(x - FACE_PAD, 0)]
roi_color = img[lower_cut[0]:upper_cut[0],lower_cut[1]]
cv2.imwrite(name,roi_color)
return sub_image()
#保存图像
def save_image(filename,img):
cv2.imwrite(filename,img)
test.py
#!/user/bin/ env python
# -*- coding:utf-8 -*-
# Author: Chen X
import cv2
import matplotlib as plt
import sys
import time
import numpy as np
from openCV第五章人脸检测和识别.faceUtil import *
filename = './liu.jpg'
face_model = " "
#output_name = "./out/%s.jpg"%(time.strftime('%Y-%m-%d-%H:%M:%S',time.localtime(time.time())))
output_name = "./%s.jpg"%(time.strftime('%Y-%m-%d-%H:%M:%S',time.localtime(time.time())))
#image_file = sys.argy[1]
#if not IMAGE_FILE):
image_name = filename
img_name = filename
#图像检测
image,img = detect_faces(model_face,img_name)
#显示图片
#plt.imshow(img)#显示图片
#plt.axis('off')#并不显示坐标轴
#plt.show()
#保存图片
save_image(output_name,img)
cv2.imshow("camer",img)
cv2.waitKey(0)
cv2.destroyAllWindows()
结果截图