我如何直接将捕获图像作为二进制数据传递以使用Python在API调用(Microsoft Cognitive Services)中进行处理 [英] How can i pass capture image directly as a binary data for processing in API calling (Microsoft Cognitive Services) using Python

查看:109
本文介绍了我如何直接将捕获图像作为二进制数据传递以使用Python在API调用(Microsoft Cognitive Services)中进行处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using Microsoft cognitive services for face and emotion recognition with python language. Now first i am capturing a image from the webcam using opencv and saving that image in a folder and in API post request i am passing image address for processing then i am getting the desired output. Now i want to save time of processing and want to capture the image from camera and send directly for processing without saving it. How can i do this using python ? Please help me i an newbie in field of programming.

这是我的代码:

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 

推荐答案

您可以使用cv.imencode在内存中对图像进行编码,然后将其发送到API.看起来类似于以下内容:

You can encode the image in memory with cv.imencode, and send that to the API. It would look something like the following:

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())

这篇关于我如何直接将捕获图像作为二进制数据传递以使用Python在API调用(Microsoft Cognitive Services)中进行处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆