如何调用 Microsoft 认知面孔并将图像作为字节 python 和 cognitive_face 传递

how to call Microsoft cognitive face and passing image as bytes python with cognitive_face

嗨,我在这个问题上尝试了同样的事情 将字节图像传递给人脸检测库 但是有了 cognitive_face 库

faces =CF.face.detect(buf.tobytes(),True,False,attributes='age,gender,emotion')

但是我遇到了一个错误

Traceback (most recent call last): File ".\cam.py", line 80, in faces = CF.face.detect(buf.tobytes(),True,False,attributes='age,gender,headPose,smile>,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,n>oise') File "Python37\lib\site-packages\cognitive_face\face.py", line 33, in detect headers, data, json = util.parse_image(image) File "Python37\lib\site-packages\cognitive_face\util.py", line 133, in parse_image elif os.path.isfile(image): # When image is a file path. File "Python37\lib\genericpath.py", line 30, in isfile st = os.stat(path) ValueError: stat: embedded null character in path

您正在使用名为 cognitive_face 的旧包,不幸的是,它希望输入参数是文件名或 URL.

幸运的是,新的包名azure-cognitiveservices-vision-face支持流,所以如果你切换过来,你可以做类似下面的事情:

from azure.cognitiveservices.vision.face import FaceClient
from msrest.authentication import CognitiveServicesCredentials
import cv2
import os

face_key = '...' # your API key
face_endpoint = '...' # your endpoint, e.g. 'https://westus.api.cognitive.microsoft.com'

credentials = CognitiveServicesCredentials(face_key)
client = FaceClient(face_endpoint, credentials)

# img is your unencoded (raw) image, from the camera
img = ...

# buf will be the encoded image
ret,buf = cv2.imencode('.jpg', img)

# stream-ify the buffer
stream = io.BytesIO(buf)

# call the Face API
detected_faces = client.face.detect_with_stream(
    stream,
    return_face_id=True,
    return_face_attributes=['age','gender','emotion'])

# access the response, example:
for detected_face in detected_faces:
    print('{} happiness probability={}'.format(
        detected_face.face_id,
        detected_face.face_attributes.emotion.happiness))