当前位置:   article > 正文

Python实现人脸识别

python实现人脸识别

叨叨几句

哈喽兄弟们,今天实现一下人脸识别

先问大家一个问题
什么是百度Aip模块?

百度AI平台提供了很多的API接口供开发者快速的调用运用在项目中
本文写的是使用百度AI的在线接口SDK模块(baidu-aip)进行实现人脸识别

除了人脸识别,其他api功能的调用也同理。

准备工作

本机环境

系统:win11
Python版本:3.9.7
编辑器:VS2022

安装baidu-aip模块

win + R 输入cmd打开命令提示符

执行安装百度AI模块

pip install baidu-aip
  • 1

登录百度AI平台创建应用

打开百度AI平台 进行登录
在控制台中找到人脸识别

按自己要求创建应用

最后得到应用的AppID API Key Secret Key

记下值 等等会用到

AppID:10000000
API Key:xxxxxxxxxxxxxxxxxxxxxxxx
Secret Key:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  • 1
  • 2
  • 3

代码流程

导入baidu-aip模块

打开VS2022(VSCode PyCharm Sypder等同理)创建一个py文件
输入

from aip import AipFace
  • 1

声明上文获取的AppID API Key Secret Key

APP_ID = '10000000'
API_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxx'
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
  • 1
  • 2
  • 3

初始化百度AIP 人脸识别模块

client = AipFace(APP_ID, API_KEY, SECRET_KEY)
  • 1

创建人脸检测函数

def face_detect(image):
    result = client.detect(image, image_type='BASE64')
    print(result)
    return result
  • 1
  • 2
  • 3
  • 4

输入的图片image必须是BASE64格式

将图片转为BASE64格式

导入base64包

import base64
  • 1

将图片打开为 BASE64格式

但是导入到百度AI中需要为字符串格式,所以返回为字符串

def imageToBase64(imagePath):
    with open(imagePath, 'rb') as f:
        image = base64.b64encode(f.read())
        return str(image, encoding='utf-8')
  • 1
  • 2
  • 3
  • 4

打开图片进行检测

先准备一张图片pic1.jpg

调用函数

face_detect(imageToBase64("pic1.jpg"))
  • 1

提示调用成功:

遇到的问题

运行时候提示:

requests.exceptions.ProxyError: HTTPSConnectionPool(host='aip.baidubce.com', port=443)
  • 1

win + R 输入 regedit打开注册表,找到

\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings
  • 1

把ProxyEnable的值改为0

再运行即可

延伸出使用其他功能

除了人脸检测还可以使用人脸比、人脸搜索对等函数,调用方法同理,比如人脸比对。

def face_match(image1, image2):
    result = client.match([
    {
        'image': image1,
        'image_type': 'BASE64',
    },
    {
        'image': image2,
        'image_type': 'BASE64',
    }
   ])
    print(result)
    return result
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

人脸搜索

def face_search(image,group_id_list):
    result = client.search(image, image_type='BASE64',group_id_list=group_id_list)
    print(result)
    return result
  • 1
  • 2
  • 3
  • 4

APP_ID API_KEY SECRET_KEY 需要修改为自己的

今天的分享就到这里结束了,完整代码点击下方V-x名片获取。

推荐一套Python教程,涵盖了常见的一百多个实战案例,每一个都非常详细。

代码总是学完就忘记?100个爬虫实战项目!让你沉迷学习丨学以致用丨下一个Python大神就是你!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/101038
推荐阅读
相关标签
  

闽ICP备14008679号