1. 程式人生 > >opencv實現簡單的人臉識別

opencv實現簡單的人臉識別

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()
結果截圖