栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

OpenCV进行人脸识别

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

OpenCV进行人脸识别

需要下载相应的库:
pip install cmake
pip install dlib

import os
import cv2
import dlib
import numpy as np
from keras.models import load_model
detector=dlib.get_frontal_face_detector()
#第二个参数表示捕获的图像分辨率
cap=cv2.VideoCapture(0,cv2.CAP_DSHOW)

margin=0.2
#设置显示的字体
font=cv2.FONT_HERSHEY_SIMPLEX
model=load_model('./models/recognition.h5')
labels={0:'cabbage',1:'car',2:'dog',3:'mobilePhone',4:'person'}
while True:
    OK,frame=cap.read()
    if OK==False:
        print('请面对摄像头!')
        break

    img_h,img_w,_=np.shape(frame)
    detected=detector(frame)
    faces=[]
    preprocess_images=[]
    if len(detected)>0:
        for i,locate in enumerate(detected):
            
            x1,y1,x2,y2,w,h=locate.left(),locate.top(),locate.right()+1,locate.bottom()+1,locate.width(),locate.height()

            xw1=max(int(x1-margin*w),0)
            yw1=max(int(y1-margin*h),0)
            xw2=min(int(x2+margin*w),img_w-1)
            yw2=min(int(y2+margin*h),img_h-1)

            cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)

            face=frame[yw1:yw2+1,xw1:xw2+1,:]
      
            face=cv2.resize(face,(128,128))
            face=face.astype('float')/255.0
            face=np.expand_dims(face,axis=0)
            preprocess_images.append(face)
        for i,d in enumerate(detected):
            preds=model.predict(preprocess_images[i])[0]
            face_labels=labels[preds.argmax()]
            cv2.putText(frame,face_labels,(d.left(),d.top()-10),font,1.2,(255,0,0),3)

        cv2.imshow('face',frame)
        if cv2.waitKey(1)&0xFF==27:
            break
cap.release()
cv2.destroyAllWindows()


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/725761.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号