使用 OpenCV 进行面部和眼睛检测

使用 OpenCV 进行面部和眼睛检测,第1张

OpenCV是构建计算机视觉应用程序的强大工具。计算机视觉中最常见的任务之一是人脸检测,它涉及识别图像或视频中人脸的存在、位置和面部特征。

在本文中,我们将学习如何使用 Haar 级联分类器检测图像中的人脸。

先决条件

在开始之前,你需要在计算机上安装 OpenCV。

参考:/releases/

你还需要一个示例图像来测试人脸检测算法。你可以使用任何你喜欢的图像。

第 1 步:加载 Haar 级联分类器

使用 OpenCV 进行面部和眼睛检测的第一步是加载 Haar 级联分类器。分类器是一个预训练的机器学习模型,经过训练可以检测人脸和眼睛。

这是加载分类器的代码:

import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
第 2 步:加载图像

接下来,我们需要加载我们要处理的图像。我们可以使用cv2模块中的imread函数来加载图像。

image = cv2.imread('Image.png')
第 3 步:将图像转换为灰度

Haar 级联分类器在灰度图像上效果最好,因此我们需要将图像转换为灰度图像。我们可以使用cvtColor函数来做到这一点。

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
第 4 步:检测人脸

现在我们可以使用级联分类器的detectMultiScale函数来检测图像中的人脸。此函数返回代表检测到的人脸位置的矩形列表。

#detect faces
faces = face_cascade.detectMultiScale(gray, 1.1, 4)

# Get the face ROI
face_roi = gray[y:y+h, x:x+w]

#detect eyes 
eyes = eye_cascade.detectMultiScale(face_roi)
第 5 步:在脸部和眼睛周围画矩形

最后,我们可以使用rectangle函数在人脸周围绘制矩形。

#Rectangle around face
for (x, y, w, h) in faces:
 cv2.rectangle(image, (x, y), (x+w, y+h), (255, 0, 0), 2)

#Rectangle around eyes
for (ex, ey, ew, eh) in eyes:
 cv2.rectangle(frame, (x+ex, y+ey), (x+ex+ew, y+ey+eh), (0, 255, 0), 2)
第 6 步:显示图像

我们可以使用imshow函数来显示带有检测到的人脸的图像。

cv2.imshow('Face Detection', image)
cv2.waitKey()
cv2.destroyAllWindows()
完整代码——检测实时视频源中的面部和眼睛import cv2

# Load the cascade classifiers for face and eye detection
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

# Start the video capture
capture = cv2.VideoCapture(0)

while True:
 # Read the frame from the video capture
 _, frame = capture.read()

 # Convert the frame to grayscale
 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

 # Detect faces in the frame
 faces = face_cascade.detectMultiScale(gray, 1.1, 4)

 # Loop over the faces
 for (x, y, w, h) in faces:
 # Draw a rectangle around the face
 cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)

 # Get the face ROI
 face_roi = gray[y:y+h, x:x+w]

 # Detect eyes in the face ROI
 eyes = eye_cascade.detectMultiScale(face_roi)

 # Loop over the eyes
 for (ex, ey, ew, eh) in eyes:
 # Draw a rectangle around the eyes
 cv2.rectangle(frame, (x+ex, y+ey), (x+ex+ew, y+ey+eh), (0, 255, 0), 2)

 # Display the frame
 cv2.imshow('Face Recognition', frame)

 # Check if the user pressed 'q' to quit
 if cv2.waitKey(1)   0xFF == ord('q'):
 break

# Release the video capture and destroy the windows
capture.release()
cv2.destroyAllWindows()

☆ END ☆
本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
DABAN RP主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
白度搜_经验知识百科全书 » 使用 OpenCV 进行面部和眼睛检测

0条评论

发表评论

提供最优质的资源集合

立即查看 了解详情