文章目录
- 前言
- 一、导入必要的库
- 二、定义函数
- 1.使用Pillow库在读取画面上添加中文文本
- 2.定义一个image_re函数方便我们多次使用
- 三、创建模型
- 四、打开摄像头
- 完毕
前言
人脸识别是计算机视觉领域最受欢迎的应用之一,广泛应用于安防监控、智能门禁、互动娱乐等场景。本文将通过Python和OpenCV库,实现一个简单的实时摄像头人脸识别程序。
一、导入必要的库
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont
二、定义函数
1.使用Pillow库在读取画面上添加中文文本
def cv2AddChineseText(img, text, position, textColor=(0, 255, 0), textSize=30):""" 向图片中添加中文 """if (isinstance(img, np.ndarray)): # 判断是否OpenCV图片类型img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) # 实现array到image的转换draw = ImageDraw.Draw(img) # 在img图片上创建一个绘图的对象# 字体的格式fontStyle = ImageFont.truetype("simsun.ttc", textSize, encoding="utf-8")draw.text(position, text, textColor, font=fontStyle) # 绘制文本return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR) # 转换回OpenCV格式
2.定义一个image_re函数方便我们多次使用
def image_re(image):a = cv2.imread(image, 0)a = cv2.resize(a, (120, 180))images.append(a)
三、创建模型
images = [] #将读取的图片装到列表里
image_re('wo.png')
image_re('wo1.png')
image_re('zly1.png')
image_re('zly2.png')labels = [0, 0, 1, 1]
recognizer = cv2.face.FisherFaceRecognizer_create(threshold=5000)
recognizer.train(images, np.array(labels))# 加载人脸检测器
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
四、打开摄像头
# 打开摄像头
cap = cv2.VideoCapture(0)while True:ret, frame = cap.read()if ret is None:breakgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)faces = faceCascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))for (x, y, w, h) in faces:face = gray[y:y+h, x:x+w]face = cv2.resize(face, (120, 180))label, confidence = recognizer.predict(face)dic = {0: '我', 1: '赵丽颖', -1: '无法识别'}text = dic.get(label, '未知')cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)frame = cv2AddChineseText(frame, text, (x, y-10), textColor=(255, 0, 0))cv2.imshow('Face Recognition', frame)if cv2.waitKey(1) == 27:breakcap.release()
cv2.destroyAllWindows()