首页 > 解决方案 > 我如何将捕获图像直接作为二进制数据传递,以便使用 Python 在 API 调用(Microsoft 认知服务)中进行处理

问题描述

我正在使用 Microsoft 认知服务通过 python 语言进行面部和情感识别。现在首先我使用opencv从网络摄像头捕获图像并将该图像保存在文件夹中,在API发布请求中我传递图像地址进行处理,然后我得到所需的输出。现在我想节省处理时间,并想从相机捕获图像并直接发送进行处理而不保存它。我如何使用 python 做到这一点?请帮助我,我是编程领域的新手。

这是我的代码:

while(True):
    ret,img=cam.read()
    faces=faceDetect.detectMultiScale(img,1.3,5)

    for(x,y,w,h) in faces:
        sampleNumber=sampleNumber+1
        cv2.imwrite("dataSet/User."+str(id)+"."+str(sampleNumber)+".jpg",img)
        cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),3)
        cv2.waitKey(10)
    cv2.imshow("Face",img)

    img_filename = "C:/Users/Robot 2/Desktop/codes_msc/dataSet/User."+str(id)+"."+str(sampleNumber)+".jpg"
with open(img_filename, 'rb') as f:
    img_data = f.read()
    header = 
    {
    # Request headers for detection
    'Content-Type': 'application/octet-stream',
    'Ocp-Apim-Subscription-Key': subscription_key
     }



  r = requests.post(api_url,
                  params=params,
                  headers=header,
                  data=img_data)
  #Here i don't want to pass img_data as an address i just want to pass image captured 

标签: pythonopencvcomputer-visionmicrosoft-cognitive

解决方案


您可以使用 对内存中的图像进行编码cv.imencode,然后将其发送到 API。它看起来像下面这样:

ret,buf = cv.imencode('.jpg', img)

headers = {
    'Content-Type':'application/octet-stream',
    'Ocp-Apim-Subscription-Key':subscription_key }

api_url = 'https://westus.api.cognitive.microsoft.com/face/v1.0/detect'

params = {
    'returnFaceLandmarks':True, 
    'returnFaceAttributes':'emotion,age,gender' }

r = requests.post(api_url,
    params=params,
    headers=headers,
    data=buf.tobytes())

推荐阅读