Python实现人脸识别
识别图片
#coding=utf-8 import requests,cv2 import re import os import bs4 #2.读取图片 filename = 'E:/Python/Crawler/faces/face7.jpg' image = cv2.imread(filename) #3.加载人脸模型 级联分类器 face_moel = cv2.CascadeClassifier('E:/Python/Crawler/faces/facemodel.xml') #4.对图片进行灰度处理 gray = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY) #5.检查人脸 faces = face_moel.detectMultiScale(gray) #6.标记人脸(椭圆形、三角形、矩形) for (x,y,w,h) in faces: #1.原始图片 2.左上角坐标 3.右下角坐标 4.颜色值 5.线宽 cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),2) #7.显示图片 cv2.imshow('Jim',image) #8.暂停窗口 cv2.waitKey(0) #9.销毁窗口 cv2.destroyAllWindows()
其中模型文件为: 人脸模型facemodel.xml
摄像头实时识别
#coding=utf-8 import requests,cv2 import re,time import os import bs4 #打开摄像头 capture = cv2.VideoCapture(0) print(type(capture)) print(capture.read()) #导入模型 #face_moel = cv2.CascadeClassifier('') face_moel = cv2.CascadeClassifier('E:/Python/Crawler/faces/facemodel.xml') c = 0 #获取摄像头的实时画面 while True: #5.读取当前摄像头一帧的画面 true false ret,image = capture.read() #6.图片灰度处理 gray = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY) #7.人脸检测 faces = face_moel.detectMultiScale(gray,1.1,3,0,(100,100)) #8.标记人脸 for (x, y, w, h) in faces: # 1.原始图片 2.左上角坐标 3.右下角坐标 4.颜色值 5.线宽 cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 5) #9.显示图片 cv2.imshow('image',image) #暂停窗口 if cv2.waitKey(5) & 0xFF == ord('q'): break #time.sleep(5) # 11.释放资源 capture.release() #12.销毁窗口 cv2.destroyAllWindows()
其中模型文件为: 人脸模型facemodel.xml