python实现图片,视频人脸识别(opencv版)

  

Python实现图片、视频人脸识别(opencv版)完整攻略

简介

OpenCV(Open Source Computer Vision)是一个开源的计算机视觉库。它最初由英特尔于1999年发起,如今是由Willow Garage、Itseez、Intel等公司和个人维护的一个跨平台计算机视觉库。OpenCV使用C++语言编写,同时支持Java、Python以及MATLAB等多种编程语言。本攻略将介绍Python下OpenCV的使用,实现图片、视频人脸识别的完整攻略。

环境配置

首先需要安装OpenCV包。使用pip安装命令即可:

pip install opencv-python

图片人脸识别

导入相关依赖和数据

import cv2 

# Load the cascade
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# Read the input image
img = cv2.imread('img.jpg')

对人脸进行检测和标记

# Convert into grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

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

# Draw rectangle around the faces
for (x, y, w, h) in faces:
    cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)

# Display the output
cv2.imshow('img', img)
cv2.waitKey()

视频人脸识别

导入相关依赖和数据

import cv2 

# Load the cascade
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# To capture video from webcam. 
cap = cv2.VideoCapture(0)

对人脸进行检测和标记

# To use a video file as input 
# cap = cv2.VideoCapture('filename.mp4')
while True:
    # Read the frame
    _, img = cap.read()

    # Convert into grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

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

    # Draw rectangle around the faces
    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)

    # Display the output
    cv2.imshow('img', img)

    # Stop if escape key is pressed
    if cv2.waitKey(1) & 0xff == ord('q'):
        break

# Release the VideoCapture object
cap.release()

以上就是Python实现图片、视频人脸识别(opencv版)的完整攻略。注意,以上示例中的 'haarcascade_frontalface_default.xml' 是OpenCV自带的人脸检测模型文件,但是只适用于正脸检测,更加精准的人脸检测可能需要使用其他模型文件。

相关文章