由于某些需要,需使用人脸识别作为基础制作一些应用,考虑到自己进行人脸识别神经网络的搭建以及训练需要耗费大量的时间,故采用API接口形式,使用face++已经训练好的人脸识别神经网络。

API接口与face++

API就是操作系统留给应用程序的一个调用接口,应用程序通过调用操作系统的 API 而使操作系统去执行应用程序的命令。不同平台的API接口调用方法可以在官网平台上找到。
face++网址:https://www.faceplusplus.com.cn/
人脸识别基础代码
face++官网图片,之后点击注册获得属于自己的API key和API Secret,如下图所示:
人脸识别基础代码

人脸识别基础例程1:网上图片识别

导入所需库

import requests

建立识别属性字符串
在此参数中的传入参数smiling,对应在返回值的attributes中参数名为smile。在使用时请注意。

attributes='gender,age,emotion,ethnicity,beauty,eyestatus,glass,skinstatus,mouthstatus,headpose,facequality,smiling'

定义识别函数,并返回识别结果r

def detect_face(image_url,api_key="自己的API KEY",api_secret="自己的API Secret",
                retrun_landmark=1,return_attributes=attributes):
    #人脸识别调用地址,在官网中可以找到
    url="https://api-cn.faceplusplus.com/facepp/v3/detect"

    #定义字典存储输入参数
    params={
        "api_key":api_key,
        "api_secret":api_secret,
        "image_url":image_url,
        "retrun_landmark":retrun_landmark,
        "return_attributes":return_attributes
    }
    r=requests.post(url=url,params=params)
    return r

在主函数中进行调用

#图片地址
img=u"http://p2.qhimgs4.com/t01342b340165fe04f3.jpg"

r=detect_face(image_url=img)
print(r)
print(r.content)

结果为,相关参数如下:

<Response [200]>  #正确调用返回标志
b'{"image_id": "RaYCG7wP2pPZ7xJhx1QW1g==", 
"request_id": "1541035219,3bbd2c48-d531-44f4-a024-2855d68d27cf", 
"time_used": 517,
 "faces": [{"attributes": {"emotion":
  {"sadness": 0.045, "neutral": 99.942, "disgust": 0.0, "anger": 0.0, "surprise": 0.007, "fear": 0.0, "happiness": 0.005}, 
 "beauty": {"female_score": 89.774, "male_score": 85.009}, 
 "gender": {"value": "Male"}, 
 "age": {"value": 22},
 "mouthstatus": {"close": 0.0, "surgical_mask_or_respirator": 0.0, "open": 100.0, "other_occlusion": 0.0},
 "glass": {"value": "None"},
 "skinstatus": {"dark_circle": 0.926, "stain": 12.231, "acne": 1.557, "health": 90.628},
 "headpose": {"yaw_angle": 9.986085, "pitch_angle": 2.3404975, "roll_angle": 13.720977}, 
 "smile": {"threshold": 50.0, "value": 0.0}, 
 "eyestatus": {"left_eye_status": {"normal_glass_eye_open": 0.006, "no_glass_eye_close": 0.0, "occlusion": 0.0, "no_glass_eye_open": 99.994, "normal_glass_eye_close": 0.0, "dark_glasses": 0.0}, "right_eye_status": {"normal_glass_eye_open": 0.117, "no_glass_eye_close": 0.0, "occlusion": 0.0, "no_glass_eye_open": 99.883, "normal_glass_eye_close": 0.0, "dark_glasses": 0.0}}, 
 "facequality": {"threshold": 70.1, "value": 81.652}, 
 "ethnicity": {"value": "ASIAN"}}, 
 "face_rectangle": {"width": 162, "top": 190, "left": 526, "height": 162}, 
 "face_token": "326665a4911a07791a0eabc19475842b"}]}'

人脸识别基础例程2:本地图片识别

需要用post multipart/form-data的方式上传,在进行图片识别,官网上有例程:https://console.faceplusplus.com.cn/documents/6329752
例程如下:
使用python3

# -*- coding: utf-8 -*-
import urllib.request
import urllib.error
import time

http_url = 'https://api-cn.faceplusplus.com/facepp/v3/detect'
key = "填上你的KEY"
secret = "填上你的SECRET"
filepath = r"本地图片的路径"

boundary = '----------%s' % hex(int(time.time() * 1000))
data = []
data.append('--%s' % boundary)
data.append('Content-Disposition: form-data; name="%s"\r\n' % 'api_key')
data.append(key)
data.append('--%s' % boundary)
data.append('Content-Disposition: form-data; name="%s"\r\n' % 'api_secret')
data.append(secret)
data.append('--%s' % boundary)
fr = open(filepath, 'rb')
data.append('Content-Disposition: form-data; name="%s"; filename=" "' % 'image_file')
data.append('Content-Type: %s\r\n' % 'application/octet-stream')
data.append(fr.read())
fr.close()
data.append('--%s' % boundary)
data.append('Content-Disposition: form-data; name="%s"\r\n' % 'return_landmark')
data.append('1')
data.append('--%s' % boundary)
data.append('Content-Disposition: form-data; name="%s"\r\n' % 'return_attributes')
data.append(
    "gender,age,smiling,headpose,facequality,blur,eyestatus,emotion,ethnicity,beauty,mouthstatus,eyegaze,skinstatus")
data.append('--%s--\r\n' % boundary)

for i, d in enumerate(data):
    if isinstance(d, str):
        data[i] = d.encode('utf-8')

http_body = b'\r\n'.join(data)

# build http request
req = urllib.request.Request(url=http_url, data=http_body)

# header
req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)

try:
    # post data to server
    resp = urllib.request.urlopen(req, timeout=5)
    # get response
    qrcont = resp.read()
    # if you want to load as json, you should decode first,
    # for example: json.loads(qrount.decode('utf-8'))
    print(qrcont.decode('utf-8'))
except urllib.error.HTTPError as e:
    print(e.read().decode('utf-8'))

自己代码如下:

import urllib.request
import urllib.error
import time

#本地图片路径
filepath = r"d:/testdata/wyb1.jpg"
#识别本地图片
#需要使用post multipart/form-data的方式上传
def faceRecongnitionDownload(filepath):
    http_url = 'https://api-cn.faceplusplus.com/facepp/v3/detect'
    key = "your KEY"
    secret = "your Secret"
    boundary = '----------%s' % hex(int(time.time() * 1000))
    data = []
    data.append('--%s' % boundary)
    data.append('Content-Disposition: form-data; name="%s"\r\n' % 'api_key')
    data.append(key)
    data.append('--%s' % boundary)
    data.append('Content-Disposition: form-data; name="%s"\r\n' % 'api_secret')
    data.append(secret)
    data.append('--%s' % boundary)
    fr = open(filepath, 'rb')
    data.append('Content-Disposition: form-data; name="%s"; filename=" "' % 'image_file')
    data.append('Content-Type: %s\r\n' % 'application/octet-stream')
    data.append(fr.read())
    fr.close()
    data.append('--%s' % boundary)
    data.append('Content-Disposition: form-data; name="%s"\r\n' % 'return_landmark')
    data.append('1')
    data.append('--%s' % boundary)
    data.append('Content-Disposition: form-data; name="%s"\r\n' % 'return_attributes')
    data.append(
    "gender,age,smiling,headpose,facequality,blur,eyestatus,emotion,ethnicity,beauty,mouthstatus,eyegaze,skinstatus")
    data.append('--%s--\r\n' % boundary)
    for i, d in enumerate(data):
        if isinstance(d, str):
            data[i] = d.encode('utf-8')

    http_body = b'\r\n'.join(data)

    # build http request
    req = urllib.request.Request(url=http_url, data=http_body)

    # header
    req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)

    try:
        # post data to server
        resp = urllib.request.urlopen(req, timeout=5)
        # get response
        qrcont = resp.read()
        # if you want to load as json, you should decode first,
        # for example: json.loads(qrount.decode('utf-8'))
       # print(qrcont.decode('utf-8'))
    except urllib.error.HTTPError as e:
        print(e.read().decode('utf-8'))
    return qrcont

#进行识别
print(faceRecongnitionDownload(filepath))

相关文章:

  • 2021-05-09
  • 2022-01-07
  • 2022-12-23
  • 2022-12-23
  • 2021-12-10
  • 2021-07-22
  • 2021-12-22
  • 2021-07-09
猜你喜欢
  • 2021-11-19
  • 2021-08-11
  • 2022-02-23
  • 2022-12-23
  • 2021-11-30
  • 2021-12-09
  • 2021-12-27
相关资源
相似解决方案