如何使用 opencv 将视频帧发送到 POST 图像 url?

How can I send a video frames in to POST image url with opencv?

我试图将单个帧发送到接收单个图像的 POST 推断模型。 这就是我想要做的: 读取单个帧转换为 base64 并发送但不工作

import requests
import base64
import io
from PIL import Image
import cv2


cap = cv2.VideoCapture(0)

if not cap.isOpened():
    print("Cannot open camera")
    exit()
while True:
    ret, frame = cap.read()
    cv2.imshow('input', frame)
    cv2.imwrite("frame.jpg", frame)
    retval, buffer = cv2.imencode('.jpg', frame)
    
    jpg_as_text = base64.b64encode(buffer)

    upload_url = "".join([
    "https://infer.roboflow.com/jb927-bottle-r6a6e--2",
    "?access_token=AHNg55YroDzs",
    "&name=frame.jpg"
    ])
    # POST to the API
    r = requests.post(upload_url, data=jpg_as_text, headers={
    "Content-Type": "application/x-www-form-urlencoded"
    })

    # Output result
    print(r.json())
    
    if cv.waitKey(1) == ord('q'):
        break

cap.release()
cv.destroyAllWindows()

看起来 base64 编码在 CV2 中正确发生。错误来自 post 请求格式。这是一个工作示例:

parts = []
url_base = 'https://infer.roboflow.com/'
endpoint = '[YOUR ENDPOINT]'
access_token = '?access_token=[YOUR KEY]'
format = '&format=json'
confidence = '&confidence=50'
parts.append(url_base)
parts.append(endpoint)
parts.append(access_token)
parts.append(format)
parts.append(confidence)
url = ''.join(parts)

print(url)

frame = cv2.imread('example_frame.jpg')

retval, buffer = cv2.imencode('.jpg', frame)
jpg_as_text = base64.b64encode(buffer)

headers = {'accept': 'application/json'}
r = requests.post(url, data=jpg_as_text, headers=headers)

print(r.json())