pythonapipostopencvroboflow

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


I trying to send individual frames to a POST infer model that receive individual images. This is what I am trying to do: read individual frames convert to base64 and send but isn't working

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


Solution

  • It looks like the base64 encoding was happening correctly with CV2. The errors came from the post request formatting. Here is a working example:

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