在这篇文章中,我们将介绍一种相当简单的方法来使用Python和OpenCV模块实现人脸识别系统,并会在代码注释中逐步解释其工作原理。
在开始之前,我们需要安装一些库来实现代码功能。下面我们将看到这些库的用途以及安装代码:
- OpenCV:
OpenCV(开源计算机视觉库)是一个开源的计算机视觉和机器学习软件库。它的构建旨在为机器学习算法和计算机视觉提供通用的基础设施。它拥有数千种经过优化的算法,可用于不同的目的,例如检测和识别人脸、识别物体等。我们需要它来使用网络摄像头拍摄照片,并对图像进行一些必要的处理。
要安装该库,您需要在系统中安装pip,之后您可以在命令提示符中按照以下步骤操作:
pip install opencv-contrib-python
- NumPy:
NumPy是Python中用于科学计算的基础包,它提供了多维数组对象,虽然可以使用它执行其他数学运算,但简而言之,我们目前只需要它将我们的图像转换为某种形式的数组,以便我们可以存储已训练的模型。
要安装该库,您可以在命令行中输入一行简单的代码:
pip install numpy
- Haar Cascade:
Haar Cascade基本上是一个分类器,用于从源中检测它已受过训练的对象。结果是一个存储训练结果的XML文件。简单来说,Haar Cascade是通过将正样本图像叠加在一组负样本图像上进行训练的。训练需要高配置的系统和良好的互联网连接以及数千张训练图像,这就是为什么它在服务器上进行的原因。为了提高结果的效率,他们使用高质量的图像并增加分类器训练的阶段数。我们需要Haar Cascade正脸识别器来从我们的网络摄像头检测人脸。
要下载不同对象的Haar Cascade文件,您可以访问以下链接:
- Python GUI (tkinter):
Tkinter是一个简单的GUI模块,用于实现相当简单的图形用户界面,帮助我们要以简单的方式与代码进行交互。虽然为了理解代码,您不必非要了解它是如何工作的。
如果您想了解更多关于Tkinter的信息,请点击下面的链接
Python GUI – tkinter
代码:使用GUI实现人脸识别的Python代码
# importing libraries
import tkinter as tk
from tkinter import Message, Text
import cv2
import os
import shutil
import csv
import numpy as np
from PIL import Image, ImageTk
import pandas as pd
import datetime
import time
import tkinter.ttk as ttk
import tkinter.font as font
from pathlib import Path
window = tk.Tk()
window.title("Face_Recogniser")
window.configure(background=‘white‘)
window.grid_rowconfigure(0, weight=1)
window.grid_columnconfigure(0, weight=1)
message = tk.Label(
window, text="Face-Recognition-System",
bg="green", fg="white", width=50,
height=3, font=(‘times‘, 30, ‘bold‘))
message.place(x=200, y=20)
lbl = tk.Label(window, text="No.",
width=20, height=2, fg="green",
bg="white", font=(‘times‘, 15, ‘ bold ‘))
lbl.place(x=400, y=200)
txt = tk.Entry(window,
width=20, bg="white",
fg="green", font=(‘times‘, 15, ‘ bold ‘))
txt.place(x=700, y=215)
lbl2 = tk.Label(window, text="Name",
width=20, fg="green", bg="white",
height=2, font=(‘times‘, 15, ‘ bold ‘))
lbl2.place(x=400, y=300)
txt2 = tk.Entry(window, width=20,
bg="white", fg="green",
font=(‘times‘, 15, ‘ bold ‘))
txt2.place(x=700, y=315)
# The function below is used for checking
# whether the text below is number or not ?
def is_number(s):
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
# Take Images is a function used for creating
# the sample of the images which is used for
# training the model. It takes 60 Images of
# every new user.
def TakeImages():
# Both ID and Name is used for recognising the Image
Id = (txt.get())
name = (txt2.get())
# Checking if the ID is numeric and name is Alphabetical
if(is_number(Id) and name.isalpha()):
# Opening the primary camera if you want to access
# the secondary camera you can mention the number
# as 1 inside the parenthesis
cam = cv2.VideoCapture(0)
# Specifying the path to haarcascade file
harcascadePath = "data\haar