当前位置:网站首页>利用opencv 做一个简单的人脸识别
利用opencv 做一个简单的人脸识别
2022-07-24 08:38:00 【MioeC】
- 想开发一个属于自己的人脸识别系统, 动手开始吧

安装
- opencv 和 包模块opencv-contrib-python
- 安装失败的解决方案
pip uninstall opencv-python
pip uninstall opencv-contrib-python
pip install opencv-python
pip install opencv-contrib-python
- 完成后重启就可以了
实现
- 先对人脸进行识别
- 获取人脸特征图片并截取 灰度图保存
- 进行人脸模型训练
- 测试运行
人脸识别
- 运用了opencv 的人脸识别框架
face_cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml')
- 截取800 帧的人脸图片 并保存数据图片
face_cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml')
VIDEO_PATH = 'video/hero2.mp4'
face_id = 2
#sampleNum用来计数样本数目
count = 0
SAVE_PATH = 'data/'
cap = cv.VideoCapture(VIDEO_PATH)
count = 0
while cap.isOpened():
ret, img = cap.read()
if ret is not None:
if img is None:
continue
img = imutils.resize(img, width=600)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
face = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in face:
cv.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0))
count += 1
if not os.path.exists(SAVE_PATH + 'user.' + str(face_id)):
os.mkdir(SAVE_PATH + 'user.' + str(face_id))
cv.imwrite(SAVE_PATH + 'user.' + str(face_id) + "/count_" + str(count) + ".jpg", gray[y: y + h, x: x + w])
if count >= 800:
break
cv.imshow('h', img)
key = cv.waitKey(1)
if key == 27:
break
else:
break
cap.release()
cv.destroyAllWindows()


测试用一个宝藏up主的人脸测试,打扰了,你要火
进行人脸模型训练
- 运用opencv 的face mok
- recog = cv.face.LBPHFaceRecognizer_create()
# 人脸识别器
import time
recog = cv.face.LBPHFaceRecognizer_create()
recog.read('trainner/face.yaml')
#创建一个函数,用于从数据集文件夹中获取训练图片,并获取id
time_start = time.process_time()
def get_imgs_labels():
face_id = 0
face_arr = []
face_ids = []
for user_id in os.listdir(SAVE_PATH):
face_id = user_id.split('.')[1]
user_path = SAVE_PATH + user_id
image_paths = [os.path.join(user_path, key) for key in os.listdir(user_path)]
for path in image_paths:
face_ids.append(int(face_id))
img = cv.imread(path, 0)
# img_arr = np.array(img, dtype="uint8")
face_arr.append(img)
return face_arr, face_ids
face_arr, face_ids = get_imgs_labels()
time_end = time.process_time ()
print('runTime' + str((time_end - time_start)))
recog.train(train_img_gen)
print('train' + str((time.process_time () - time_end)))
recog.save('trainner/face.yaml')
- 训练完保存了一个模型文件

识别人脸测试
- 先用人脸识别出人脸区域,截取出人脸区域,进行灰度化
- 输入到模型中预测
- 图片展示
VIDEO_PATH = 'video/hero3.mp4'
font = cv.FONT_HERSHEY_SIMPLEX
idNum = 0
names = ['unknow', 'cc', 'dm']
cap = cv.VideoCapture(VIDEO_PATH)
while cap.isOpened():
ret, img = cap.read()
img = imutils.resize(img, width=600)
if ret is not None:
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
face = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in face:
cv.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0))
id, conf = recog.predict(gray[y: y+h, x: x+w])
user = ''
if conf < 100:
user = names[id]
conf = "{0}%".format(round(100-conf))
else:
user = "unknown"
conf = "{0}%".format(round(100-conf))
cv.putText(img, user, (x + 5, y - 5), font, 1, (0,255, 0), 1)
cv.putText(img, str(conf), (x + 50, y - 5), font, 1, (0,255, 0), 1)
cv.imshow('face', img)
key = cv.waitKey(1)
if key == 27:
break
cap.release()
cv.destroyAllWindows()
效果展示


- 下面这个是训练的视频,上面是测试的视频
完整代码
# %%
import cv2 as cv
import numpy as np
import imutils
import os
from PIL import Image
# %%
face_cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml')
VIDEO_PATH = 'video/hero2.mp4'
face_id = 2
#sampleNum用来计数样本数目
count = 0
SAVE_PATH = 'data/'
cap = cv.VideoCapture(VIDEO_PATH)
count = 0
while cap.isOpened():
ret, img = cap.read()
if ret is not None:
if img is None:
continue
img = imutils.resize(img, width=600)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
face = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in face:
cv.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0))
count += 1
if not os.path.exists(SAVE_PATH + 'user.' + str(face_id)):
os.mkdir(SAVE_PATH + 'user.' + str(face_id))
cv.imwrite(SAVE_PATH + 'user.' + str(face_id) + "/count_" + str(count) + ".jpg", gray[y: y + h, x: x + w])
if count >= 800:
break
cv.imshow('h', img)
key = cv.waitKey(1)
if key == 27:
break
else:
break
cap.release()
cv.destroyAllWindows()
# %%
import tensorflow.keras as keras
from keras.preprocessing.image import ImageDataGenerator
train_gen = ImageDataGenerator(rescale= 1./255)
train_img_gen = train_gen.flow_from_directory('./data/')
# %%
# 人脸识别器
import time
recog = cv.face.LBPHFaceRecognizer_create()
recog.read('trainner/face.yaml')
#创建一个函数,用于从数据集文件夹中获取训练图片,并获取id
time_start = time.process_time()
def get_imgs_labels():
face_id = 0
face_arr = []
face_ids = []
for user_id in os.listdir(SAVE_PATH):
face_id = user_id.split('.')[1]
user_path = SAVE_PATH + user_id
image_paths = [os.path.join(user_path, key) for key in os.listdir(user_path)]
for path in image_paths:
face_ids.append(int(face_id))
img = cv.imread(path, 0)
# img_arr = np.array(img, dtype="uint8")
face_arr.append(img)
return face_arr, face_ids
face_arr, face_ids = get_imgs_labels()
time_end = time.process_time ()
print('runTime' + str((time_end - time_start)))
recog.train(train_img_gen)
print('train' + str((time.process_time () - time_end)))
recog.save('trainner/face.yaml')
# %%
VIDEO_PATH = 'video/hero2.mp4'
font = cv.FONT_HERSHEY_SIMPLEX
idNum = 0
names = ['unknow', 'cc', 'dm']
cap = cv.VideoCapture(VIDEO_PATH)
while cap.isOpened():
ret, img = cap.read()
img = imutils.resize(img, width=600)
if ret is not None:
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
face = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in face:
cv.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0))
id, conf = recog.predict(gray[y: y+h, x: x+w])
user = ''
if conf < 100:
user = names[id]
conf = "{0}%".format(round(100-conf))
else:
user = "unknown"
conf = "{0}%".format(round(100-conf))
cv.putText(img, user, (x + 5, y - 5), font, 1, (0,255, 0), 1)
cv.putText(img, str(conf), (x + 50, y - 5), font, 1, (0,255, 0), 1)
cv.imshow('face', img)
key = cv.waitKey(1)
if key == 27:
break
cap.release()
cv.destroyAllWindows()
# %%
边栏推荐
- Limited and unlimited Games: crypto
- Dao race track is booming. What are the advantages of m-dao?
- Take out the string in brackets
- Mysql database advanced
- From starfish OS' continued deflationary consumption of SFO, the value of SFO in the long run
- Optimization of MySQL paging query
- Larave uses sanctum for API authentication
- [emotion] what is "excellent"
- 使用Go语言开发eBPF程序
- Oauth2 server set up oauth2 authentication service
猜你喜欢

Precautions for using kettle excel input

JS string interception

Play to earn: a new and more promising game paradigm in the future

Move protocol launched a beta version, and you can "0" participate in p2e

Mysql database advanced

【FFH】OpenHarmony啃论文成长计划---cJSON在传统C/S模型下的应用

面试官:哥们Go语言的读写锁了解多少?

Encryption market ushers in a new historical cycle. Look at jpex's "stability" and "health"

"Problem solution" with score

Aquanee: the true meaning of "p2e"
随机推荐
4、 Midway integrates swagger and supports JWT bearers
【一起上水硕系列】一起提前看看July课程
Wargames NATAS (11-15) problem solving essay
Source code analysis of BlockingQueue (arraybq and linkedbq)
Go:gin write test code
Private traffic + apps, new opportunities for e-commerce drainage
Summary of points management system project
table-rowspan
Do you know the private domain traffic in app?
After two days of tossing and turning, I finally wrote my first fluent app, which almost tortured me into a nervous breakdown
Shanghai issued a document to support the entry of NFT cultural exchange: the trend of digital collections has arrived!
Clear up some disk space and try again
Move protocol launched a beta version, and you can "0" participate in p2e
1、 Midwey addition, deletion, modification and query
Why does the metauniverse need NFT?
Look at the most influential infrastructure m-dao of Web3 through the current situation of Dao
Ubuntu20.04 install MySQL 5.7
「题解」带分数
Beandefinition three ways to load beans
Use the bark app to realize the process of pushing messages to mobile phones