python人脸识别代码实现
生活随笔
收集整理的這篇文章主要介紹了
python人脸识别代码实现
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1.識別圖片中的人臉位置
#人臉識別分類器路徑 tool_url = r'C:\Users\86188\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml' #人臉定位函數(shù) def face_detect(img):gray = cv.cvtColor(img,cv.COLOR_BGRA2BGR)face = cv.CascadeClassifier(tool_url)#將圖片轉(zhuǎn)化為灰度圖faces = face.detectMultiScale(gray)#確定人臉部分for x,y,w,h in faces:reg = cv.rectangle(img, (x, y),( x + w, y + h), color=(0, 255, 0), thickness=2)cv.imshow("reg",reg)2.根據(jù)訓(xùn)練集訓(xùn)練數(shù)據(jù)并保存(dataTraining.py)
import os import cv2 as cv import numpy from PIL import Image ''' 訓(xùn)練數(shù)據(jù)來自s2和s9 '''def getImageAndIds(path):facesSimples = []ids = []img_paths = [os.path.join(path,f) for f in os.listdir(path)]#檢測人臉tool_url = r'C:\Users\86188\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml'# 調(diào)用插件獲取圖像特征face = cv.CascadeClassifier(tool_url)for i in img_paths:# print(i)img = Image.open(i).convert("L")# Image._show(img)#將圖片轉(zhuǎn)換為數(shù)組img_np = numpy.array(img,'uint8')# print(img_np)# 獲取圖像的人臉信息和對應(yīng)idfaces = face.detectMultiScale(img_np)id = int(i.split(path)[1].split('.')[0])for x, y, w, h in faces:facesSimples.append(img_np[y:y+h,x:x+w])ids.append(id)return facesSimples,idsif __name__ == "__main__":#圖片路徑path = "./data/"faces,ids = getImageAndIds(path)#獲取循環(huán)對象reg = cv.face.LBPHFaceRecognizer_create()reg.train(faces,numpy.array(ids))#保存文件reg.write("trainer/trainer.yml")3.人臉識別(faceChecking.py)
import cv2 as cv import os,numpy#檢測人臉 tool_url = r'C:\Users\86188\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml' #圖片數(shù)據(jù)路徑 path = './data/' # 調(diào)用插件獲取圖像特征 face = cv.CascadeClassifier(tool_url)#加載訓(xùn)練數(shù)據(jù) reg = cv.face.LBPHFaceRecognizer_create() reg.read("trainer/trainer.yml")img= cv.imread("3.jpg") #將圖像的人臉特征圈出來 gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY) faces = face.detectMultiScale(gray) for x, y, w, h in faces:# print(x,y,w,h)cv.rectangle(gray, (x, y), (x + w, y + h), color=(0, 0, 255), thickness=2)#檢測出識別后的圖片和idid,configence = reg.predict(gray[y:y+h,x:x+w])#顯示對應(yīng)圖片print("編號:{},置信度:{}".format(id,configence))aim_img = cv.imread(os.path.join(path,str(id)+'.jpg'))#顯示目標(biāo)圖片cv.imshow("aim_img",aim_img)cv.imshow("result",gray) cv.waitKey(0) cv.destroyAllWindows()總結(jié)
以上是生活随笔為你收集整理的python人脸识别代码实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Comet OJ CCPC-Wannaf
- 下一篇: 人脸识别Python教学