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

如何将捕获图像作为二进制数据直接传递,以便在使用Python的API调用(Microsoft认知服务)中进行处理,python,opencv,computer-vision,microsoft-cognitive,Python,Opencv,Computer Vision,Microsoft Cognitive,我正在使用Microsoft认知服务与python语言进行人脸和情绪识别。 现在,首先我使用opencv从网络摄像头捕获一幅图像,并将该图像保存在一个文件夹中,然后在API post请求中传递图像地址以进行处理,然后获得所需的输出。 现在,我想节省处理时间,并希望从相机捕获图像,直接发送进行处理,而不保存它。如何使用python实现这一点? 请帮助我,我是编程领域的新手 这是我的密码: while(True): ret,img=cam.read() faces=faceDetec

我正在使用Microsoft认知服务与python语言进行人脸和情绪识别。 现在,首先我使用opencv从网络摄像头捕获一幅图像,并将该图像保存在一个文件夹中,然后在API post请求中传递图像地址以进行处理,然后获得所需的输出。 现在,我想节省处理时间,并希望从相机捕获图像,直接发送进行处理,而不保存它。如何使用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 

您可以使用
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())

您可以使用
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())

我成功了,img_data=cv2.imencode('.jpg',img)img_data=img_data.tobytes()我成功了,img_data=cv2.imencode('.jpg',img)img_data=img_data.tobytes()