热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

基于Python与命令行人脸识别项目(系列二)

接着系统一,继续开始我们face_recognition.Python模块:face_recognition在Python中,你可以导入face_recognition模块,调用丰

接着系统一,继续开始我们face_recognition.


Python 模块:face_recognition

在Python中,你可以导入face_recognition模块,调用丰富的API接口,用几行代码就可以轻松玩转各种人脸识别功能!

API 接口文档: https://face-recognition.readthedocs.io(可以参考这个)


在图片中定位人脸的位置关键代码

import face_recognition
image = face_recognition.load_image_file("my_picture.jpg")
face_locations = face_recognition.face_locations(image)
# face_locations is now an array listing the co-ordinates of each face!
看定位鞠婧祎的脸:在knowe_people文件夹中创建find_faces_in_picture.py文件并写入以下代码:
from PIL import Image
import face_recognition
# Load the jpg file into a numpy array
image = face_recognition.load_image_file("鞠婧祎.jpeg")
# Find all the faces in the image using the default HOG-based model.
# This method is fairly accurate, but not as accurate as the CNN model and not GPU accelerated.
# See also: find_faces_in_picture_cnn.py
face_locatiOns= face_recognition.face_locations(image)
print("I found {} face(s) in this photograph.".format(len(face_locations)))
for face_location in face_locations:
    # Print the location of each face in this image
    top, right, bottom, left = face_location
    print("A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right))
    # You can access the actual face itself like this:
    face_image = image[top:bottom, left:right]
    pil_image = Image.fromarray(face_image)
    pil_image.show()
然后终端切换到knowe_people目录下,输入以下命令,弹出窗口如下:
技术分享图片

 

可以看到终端已经找到鞠婧祎人脸坐标分别是:Top: 297, Left: 553, Bottom: 759, Right: 1016,并输出人脸。继续测试

将第二段第二行改为image = face_recognition.load_image_file("特朗普.jpg"),终端输出如下:
技术分享图片

你也可以使用深度学习模型达到更加精准的人脸定位。

注意:这种方法需要GPU加速(通过英伟达显卡的CUDA库驱动),你在编译安装dlib的时候也需要开启CUDA支持。


import face_recognition
image = face_recognition.load_image_file("my_picture.jpg")
face_locations = face_recognition.face_locations(image, model="cnn")
# face_locations is now an array listing the co-ordinates of each face!
看案例:利用卷积神经网络深度学习模型定位鞠婧祎的人脸

在knowe_people文件夹中创建find_faces_in_picture_cnn.py文件并写入以下代码:
from PIL import Image
import face_recognition
# Load the jpg file into a numpy array
image = face_recognition.load_image_file("鞠婧祎.jpg")
# Find all the faces in the image using a pre-trained convolutional neural network.
# This method is more accurate than the default HOG model, but it‘s slower
# unless you have an nvidia GPU and dlib compiled with CUDA extensions. But if you do,
# this will use GPU acceleration and perform well.
# See also: find_faces_in_picture.py
face_locatiOns= face_recognition.face_locations(image, number_of_times_to_upsample=0, model="cnn")
print("I found {} face(s) in this photograph.".format(len(face_locations)))
for face_location in face_locations:
    # Print the location of each face in this image
    top, right, bottom, left = face_location
    print("A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right))
    # You can access the actual face itself like this:
    face_image = image[top:bottom, left:right]
    pil_image = Image.fromarray(face_image)
    pil_image.show()

然后终端切换到knowe_people目录下,输入以下命令,弹出窗口如下:

技术分享图片


如果你有很多图片需要识别,同时又有GPU,那么你可以参考这个例子:

案例:利用卷积神经网络深度学习模型批量识别人脸照片

在knowe_people文件夹中创建find_faces_in_batches.py文件并写入以下代码:
import face_recognition
import cv2
# This code finds all faces in a list of images using the CNN model.
#
# This demo is for the _special case_ when you need to find faces in LOTS of images very quickly and all the images
# are the exact same size. This is common in video processing applications where you have lots of video frames
# to process.
#
# If you are processing a lot of images and using a GPU with CUDA, batch processing can be ~3x faster then processing
# single images at a time. But if you aren‘t using a GPU, then batch processing isn‘t going to be very helpful.
#
# PLEASE NOTE: This example requires OpenCV (the `cv2` library) to be installed only to read the video file.
# OpenCV is *not* required to use the face_recognition library. It‘s only required if you want to run this
# specific demo. If you have trouble installing it, try any of the other demos that don‘t require it instead.
# Open video file
video_capture = cv2.VideoCapture("short_hamilton_clip.mp4")
frames = []
frame_count = 0
while video_capture.isOpened():
    # Grab a single frame of video
    ret, frame = video_capture.read()
    # Bail out when the video file ends
    if not ret:
        break
    # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
    frame = frame[:, :, ::-1]
    # Save each frame of the video to a list
    frame_count += 1
    frames.append(frame)
    # Every 128 frames (the default batch size), batch process the list of frames to find faces
    if len(frames) == 128:
        batch_of_face_locatiOns= face_recognition.batch_face_locations(frames, number_of_times_to_upsample=0)
        # Now let‘s list all the faces we found in all 128 frames
        for frame_number_in_batch, face_locations in enumerate(batch_of_face_locations):
            number_of_faces_in_frame = len(face_locations)
            frame_number = frame_count - 128 + frame_number_in_batch
            print("I found {} face(s) in frame #{}.".format(number_of_faces_in_frame, frame_number))
            for face_location in face_locations:
                # Print the location of each face in this frame
                top, right, bottom, left = face_location
                print(" - A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right))
        # Clear the frames array to start the next batch
        frames = []
注意到:这个例子需要安装openCV.这个例子需要GPU cuda加速,否则运行卡顿。我就试了几次,电脑死机,先跳过,以后再说。
案例:使用卷积神经网络深度学习模型把来自网络摄像头视频的人脸高斯模糊。

在knowe_people文件夹中创建blur_faces_on_webcam.py文件并写入以下代码:
import face_recognition
import cv2
# This is a demo of blurring faces in video.
# PLEASE NOTE: This example requires OpenCV (the `cv2` library) to be installed only to read from your webcam.
# OpenCV is *not* required to use the face_recognition library. It‘s only required if you want to run this
# specific demo. If you have trouble installing it, try any of the other demos that don‘t require it instead.
# Get a reference to webcam #0 (the default one)
video_capture = cv2.VideoCapture(0)
# Initialize some variables
face_locatiOns= []
while True:
    # Grab a single frame of video
    ret, frame = video_capture.read()
    # Resize frame of video to 1/4 size for faster face detection processing
    small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
    # Find all the faces and face encodings in the current frame of video
    face_locatiOns= face_recognition.face_locations(small_frame, model="cnn")
    # Display the results
    for top, right, bottom, left in face_locations:
        # Scale back up face locations since the frame we detected in was scaled to 1/4 size
        top *= 4
        right *= 4
        bottom *= 4
        left *= 4
        # Extract the region of the image that contains the face
        face_image = frame[top:bottom, left:right]
        # Blur the face image
        face_image = cv2.GaussianBlur(face_image, (99, 99), 30)
        # Put the blurred face region back into the frame image
        frame[top:bottom, left:right] = face_image
    # Display the resulting image
    cv2.imshow(‘Video‘, frame)
    # Hit ‘q‘ on the keyboard to quit!
    if cv2.waitKey(1) & 0xFF == ord(‘q‘):
        break
# Release handle to the webcam
video_capture.release()
cv2.destroyAllWindows()

然后终端切换到knowe_people目录下,输入以下命令,弹出窗口如下:(把自己宿舍卖了,希望室友不要介意,嘻嘻)
技术分享图片
好了,今天就到这吧,今天主要实现4个功能(如下),更多功能见系列三。

案例一:定位鞠婧祎的脸

案例二:利用卷积神经网络深度学习模型定位鞠婧祎的人脸

案例三:利用卷积神经网络深度学习模型批量识别人脸照片

案例四:使用卷积神经网络深度学习模型把来自网络摄像头视频的人脸高斯模糊。



推荐阅读
  • 网络爬虫的规范与限制
    本文探讨了网络爬虫引发的问题及其解决方案,重点介绍了Robots协议的作用和使用方法,旨在为网络爬虫的合理使用提供指导。 ... [详细]
  • 如果应用程序经常播放密集、急促而又短暂的音效(如游戏音效)那么使用MediaPlayer显得有些不太适合了。因为MediaPlayer存在如下缺点:1)延时时间较长,且资源占用率高 ... [详细]
  • 自然语言处理(NLP)——LDA模型:对电商购物评论进行情感分析
    目录一、2020数学建模美赛C题简介需求评价内容提供数据二、解题思路三、LDA简介四、代码实现1.数据预处理1.1剔除无用信息1.1.1剔除掉不需要的列1.1.2找出无效评论并剔除 ... [详细]
  • 本文介绍了Java编程语言的基础知识,包括其历史背景、主要特性以及如何安装和配置JDK。此外,还详细讲解了如何编写和运行第一个Java程序,并简要介绍了Eclipse集成开发环境的安装和使用。 ... [详细]
  • malloc 是 C 语言中的一个标准库函数,全称为 memory allocation,即动态内存分配。它用于在程序运行时申请一块指定大小的连续内存区域,并返回该区域的起始地址。当无法预先确定内存的具体位置时,可以通过 malloc 动态分配内存。 ... [详细]
  • Python多线程详解与示例
    本文介绍了Python中的多线程编程,包括僵尸进程和孤儿进程的概念,并提供了具体的代码示例。同时,详细解释了0号进程和1号进程在系统中的作用。 ... [详细]
  • Spring Data JdbcTemplate 入门指南
    本文将介绍如何使用 Spring JdbcTemplate 进行数据库操作,包括查询和插入数据。我们将通过一个学生表的示例来演示具体步骤。 ... [详细]
  • 本文节选自《NLTK基础教程——用NLTK和Python库构建机器学习应用》一书的第1章第1.2节,作者Nitin Hardeniya。本文将带领读者快速了解Python的基础知识,为后续的机器学习应用打下坚实的基础。 ... [详细]
  • 利用python爬取豆瓣电影Top250的相关信息,包括电影详情链接,图片链接,影片中文名,影片外国名,评分,评价数,概况,导演,主演,年份,地区,类别这12项内容,然后将爬取的信息写入Exce ... [详细]
  • 解决Only fullscreen opaque activities can request orientation错误的方法
    本文介绍了在使用PictureSelectorLight第三方框架时遇到的Only fullscreen opaque activities can request orientation错误,并提供了一种有效的解决方案。 ... [详细]
  • 本文详细介绍了如何解决DNS服务器配置转发无法解析的问题,包括编辑主配置文件和重启域名服务的具体步骤。 ... [详细]
  • importpymysql#一、直接连接mysql数据库'''coonpymysql.connect(host'192.168.*.*',u ... [详细]
  • Bootstrap 缩略图展示示例
    本文将展示如何使用 Bootstrap 实现缩略图效果,并提供详细的代码示例。 ... [详细]
  • 为什么多数程序员难以成为架构师?
    探讨80%的程序员为何难以晋升为架构师,涉及技术深度、经验积累和综合能力等方面。本文将详细解析Tomcat的配置和服务组件,帮助读者理解其内部机制。 ... [详细]
  • 浅析python实现布隆过滤器及Redis中的缓存穿透原理_python
    本文带你了解了位图的实现,布隆过滤器的原理及Python中的使用,以及布隆过滤器如何应对Redis中的缓存穿透,相信你对布隆过滤 ... [详细]
author-avatar
入骨红豆撕不撕
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有