python调用face++API并保存输出结果(表情识别API)

  • 图片不用一张张调用,这个代码一次性从文件夹中提取照片的文件名,对文件夹中的每张照片调用API并输出结果。
  • 可以选择需要的输出,比如happiness的百分制值,headpose等等。
  • 结果直接写入到txt文档中。

首先需要去face++官网申请一个API,是免费的。这个网页可以申请,并且可以本地上传图片看一下识别效果。
https://www.faceplusplus.com.cn/emotion-recognition/#demo

然后似乎就只要把下面的python代码运行一下就好了,要填的地方我标注了,最后数据会输出在名为“1.txt”的文本文档中,感觉没什么特别要说明的了,要是有问题可以留言什么的问我2333

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


def file_name(file_dir):

    list1 = []
    for root, dirs, files in os.walk(file_dir):
        for file in files:
            if os.path.splitext(file)[1] == '.jpg':
                list1.append(os.path.join(root, file))
    return list1


L = file_name(r"这里填入包含所需检测图片的文件夹的地址")
L.sort(key=len)
http_url = 'https://api-cn.faceplusplus.com/facepp/v3/detect'
key = "这里填入face++的key"
secret = "这里填入face++的secret"

file_handle = open('1.txt', mode='w')

for filepath in L:
    # filepath = rootdir
    print(filepath)
    x = filepath + '\n'
    file_handle.write(x)
    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'))

    mydict = eval(qrcont)
    faces = mydict["faces"]
    faceNum = len(faces)
    x = str(faceNum) + '\n'
    file_handle.write(x)

    for i in range(faceNum):
        attributes = faces[i]['attributes']

        emotion = attributes['emotion']
        anger = emotion['anger']
        disgust = emotion['disgust']
        fear = emotion['fear']
        happiness = emotion['happiness']
        neutral = emotion['neutral']
        sadness = emotion['sadness']
        surprise = emotion['surprise']
        x = str(anger) + '\n'
        file_handle.write(x)
        x = str(disgust) + '\n'
        file_handle.write(x)
        x = str(fear) + '\n'
        file_handle.write(x)
        x = str(happiness) + '\n'
        file_handle.write(x)
        x = str(neutral) + '\n'
        file_handle.write(x)
        x = str(sadness) + '\n'
        file_handle.write(x)
        x = str(surprise) + '\n'
        file_handle.write(x)

        headpose = attributes['headpose']
        pitch_angle = headpose['pitch_angle']
        roll_angle = headpose['roll_angle']
        yaw_angle = headpose['yaw_angle']
        x = str(pitch_angle) + '\n'
        file_handle.write(x)
        x = str(roll_angle) + '\n'
        file_handle.write(x)
        x = str(yaw_angle) + '\n'
        file_handle.write(x)

        blur = attributes['blur']
        blurness = blur['blurness']
        value = blurness['value']
        x = str(value) + '\n'
        file_handle.write(x)

file_handle.close()

你可能感兴趣的:(表情识别)