Face Recognition: Python Implementation

Face Recognition: Python Implementation

Facial recognition is an important feature of artificial intelligence (AI), which allows computers to identify who a person is. In this article, we will introduce how to use Python to implement face recognition.

Implemented using openCV

OpenCV is an open-source library that supports a variety of applications in image processing, computer vision, and machine learning, including face recognition. Below we use OpenCV to implement a simple face recognition function.

Preparation

First, we need to install the OpenCV library and various related packages of Python, as follows:

pip install opencv-python
pip install opencv-contrib-python
pip install numpy

Then, we need to prepare some sample photos, which will be used to train the model and finally detect who is who. Only people who appear in the sample photo can be identified.

training model

In the next step, we need to train the model to realize face recognition. We use the OpenCV face_recognitionmodule to train the model. as follows:

import cv2

# 读取样本照片,存入列表
images = []

for i in range(1, 5):
  image = cv2.imread('sample' + str(i) + '.jpg')
  images.append(image)

# 训练模型
model = cv2.face.createFisherFaceRecognizer()
model.train(images, labels)

face recognition

After completing the model training, we can start to perform face recognition on the images read by the camera. We can use OpenCV detectMultiScaleto find a face in an image and use predicta function to predict the identity of that person.

import cv2

# 读取图片
image = cv2.imread('input.jpg')

# 找出图片中的人脸
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)

# 预测每一张脸的身份
for (x, y, w, h) in faces:
  roi = gray[y:y + h, x:x + w]
  label = model.predict(roi)
  print(label)

in conclusion

This article introduces how to use Python to implement face recognition. We use the OpenCV module to train the model, and use it detectMultiScaleto find faces, and finally use it predictto predict the identity of each face.

Guess you like

Origin blog.csdn.net/weixin_50814640/article/details/129449277