使用 OpenCV 进行人脸检测

磐创AI
关注

使用 OpenCV 和 Python 检测人脸的一种非常流行且简单的方法

步骤 01

我为此使用 Google Colab,首先,请确保你已安装 OpenCV。你可以使用 pip 安装它:

pip install opencv-python

步骤 02

请确保这些库已经安装。

import cv2

pip install numpy

pip install matplotlib

步骤 03

在检测人脸之前,我们必须使用 Google Colab 打开网络摄像头。

from google.colab.patches import cv2_imshow

步骤 04

运行这两个代码后,网络摄像头打开,你可以拍张照片。

from IPython.display import display, Javascript

from google.colab.output import eval_js

from base64 import b64decode

def take_photo(filename='photo.jpg', quality=0.8):

js = Javascript('''

async function takePhoto(quality) {

const div = document.createElement('div');

const capture = document.createElement('button');

capture.textContent = 'Capture';

div.appendChild(capture);

const video = document.createElement('video');

video.style.display = 'block';

const stream = await navigator.mediaDevices.getUserMedia({video: true});

document.body.appendChild(div);

div.appendChild(video);

video.srcObject = stream;

await video.play();

// Resize the output to fit the video element.

google.colab.output.setIframeHeight(document.documentElement.scrollHeight, true);

// Wait for Capture to be clicked.

await new Promise((resolve) => capture.onclick = resolve);

const canvas = document.createElement('canvas');

canvas.width = video.videoWidth;

canvas.height = video.videoHeight;

canvas.getContext('2d').drawImage(video, 0, 0);

stream.getVideoTracks()[0].stop();

div.remove();

return canvas.toDataURL('image/jpeg', quality);

''')

   display(js)

   data = eval_js('takePhoto({})'.format(quality))

   binary = b64decode(data.split(',')[1])

   with open(filename, 'wb') as f:

   f.write(binary)

   return filename


from IPython.display import Image

try:

filename = take_photo()

print('Saved to {}'.format(filename))

# Show the image which was just taken.

display(Image(filename))

except Exception as err:

# Errors will be thrown if the user does not have a webcam or if they do not

# grant the page permission to access it.

print(str(err))

照片保存为 photo.jpg。

photo.jpg

使用 Haar 级联的人脸检测是一种基于机器学习的方法,其中使用一组输入数据训练级联函数。OpenCV 已经包含许多针对面部、眼睛、微笑等的预训练分类器。今天我们将使用面部分类器。你也可以尝试使用其他分类器。

要检测图像中的人脸:

步骤 05

import cv2

img = cv2.imread('photo.jpg')

gray_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')


eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')

nose_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_nose.xml')

# detect all the faces in the image

faces = face_cascade.detectMultiScale(gray_img,1.1,4)

# print the number of faces detected

print(f"{len(faces)} faces detected in the image.")

对于每个人脸,绘制一个绿色矩形:

步骤 06

for x, y, width, height in faces:

cv2.rectangle(img, (x, y), (x + width, y + height), color=(0, 255, 0), thickness=2)

用矩形保存图像:

步骤 07

# save the image with rectangles

cv2.imwrite("photo_detected.jpg", img)

转到文件 photo_detected.jpg 并打开 。

结果:

photo_detected.jpg


       原文标题 : 使用 OpenCV 进行人脸检测

声明: 本文由入驻OFweek维科号的作者撰写,观点仅代表作者本人,不代表OFweek立场。如有侵权或其他问题,请联系举报。
侵权投诉

下载OFweek,一手掌握高科技全行业资讯

还不是OFweek会员,马上注册
打开app,查看更多精彩资讯 >
  • 长按识别二维码
  • 进入OFweek阅读全文
长按图片进行保存