user8483278
user8483278

Reputation:

How to send image from openCV to a Web API

I have a web camera and I can capture video from it as following:

import cv2
cap = cv2.VideoCapture(0)
while True:
    ret, frame = cap.read()

    cv2.imshow('frame', frame)
    if cv2.waitKey(1) and 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()

What I want to do is to send the frame to an Web API (HTTP), receive the response image and show that image. I'm new to openCV. Would you tell me how do I do this?

Upvotes: 1

Views: 3695

Answers (1)

Artur Barseghyan
Artur Barseghyan

Reputation: 14172

Try this (taken from a real project). Some parts (authentication, response validation) are obviously skipped. Hopefully it will give you a good grasp.

import cv2
from PIL import Image
from six import StringIO
import requests


cap = cv2.VideoCapture(0)
while True:
    ret, frame = cap.read()

    cv2.imshow('frame', frame)
    if cv2.waitKey(1) and 0xFF == ord('q'):

        frame_im = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        pil_im = Image.fromarray(frame_im)
        stream = StringIO()
        pil_im.save(stream, format="JPEG")
        stream.seek(0)
        img_for_post = stream.read()    
        files = {'image': img_for_post}
        response = requests.post(
            url='/api/path-to-your-endpoint/',
            files=files
        )

        break

cap.release()
cv2.destroyAllWindows()

Upvotes: 1

Related Questions