Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Send and receive images using Flask, Numpy and OpenCV
import requests
import json
import cv2
addr = 'http://localhost:5000'
test_url = addr + '/api/test'
# prepare headers for http request
content_type = 'image/jpeg'
headers = {'content-type': content_type}
img = cv2.imread('lena.jpg')
# encode image as jpeg
_, img_encoded = cv2.imencode('.jpg', img)
# send http request with image and receive response
response = requests.post(test_url, data=img_encoded.tostring(), headers=headers)
# decode response
print json.loads(response.text)
# expected output: {u'message': u'image received. size=124x124'}
from flask import Flask, request, Response
import jsonpickle
import numpy as np
import cv2
# Initialize the Flask application
app = Flask(__name__)
# route http posts to this method
@app.route('/api/test', methods=['POST'])
def test():
r = request
# convert string of image data to uint8
nparr = np.fromstring(r.data, np.uint8)
# decode image
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
# do some fancy processing here....
# build a response dict to send back to client
response = {'message': 'image received. size={}x{}'.format(img.shape[1], img.shape[0])
}
# encode response using jsonpickle
response_pickled = jsonpickle.encode(response)
return Response(response=response_pickled, status=200, mimetype="application/json")
# start flask app
app.run(host="0.0.0.0", port=5000)
@mario-grgic

This comment has been minimized.

Copy link

mario-grgic commented May 12, 2017

You don't really need OpenCV to post an image. requests alone is enough.

def post_image(img_file):
    """ post image and return the response """
    img = open(img_file, 'rb').read()
    response = requests.post(URL, data=img, headers=headers)
    return response

@nlhkh

This comment has been minimized.

Copy link

nlhkh commented Sep 28, 2017

Sometimes this can be useful when you process an image before sending

@santhoshdc1590

This comment has been minimized.

Copy link

santhoshdc1590 commented Apr 7, 2018

Sometimes you might not even have a code running at the other end to imdecode which is exactly what happened with me. Where I had to upload an image directly onto google-cloud-storage
Here's a solution I came up with

from google.cloud import storage
import cv2
from tempfile import NamedTemporaryFile
import six

client = storage.Client()
#specify google bucket name
bucket = client.get_bucket('doc')

#image to be loaded
image = cv2.imread('24.jpg')

with NamedTemporaryFile() as temp:
    #add JPEG format to the NamedTemporaryFile  
    iName = "".join([str(temp.name),".jpg"])
    
    #save the numpy array image onto the NamedTemporaryFile
    cv2.imwrite(iName,image)
    #Name of the file in the bucket
    blob = bucket.blob('T15.jpg')
    #Type of file being uploaded
    blob.upload_from_filename(iName,content_type='image/jpeg')
    #get the public url
    url = blob.public_url
    print(type(url))
@kaskavalci

This comment has been minimized.

Copy link

kaskavalci commented Aug 21, 2018

Thanks for this! I hit a problem where I needed to encode the image before sending and decode it again. If you convert the image into gray scale and use the received image in dlib (face_recognition) then library complains with RuntimeError: Unsupported image type, must be 8bit gray or RGB image.. Encoding and decoding to cv2.IMREAD_COLOR helped me solve this problem. Decoding the payload to IMREAD_GRAYSCALE didn't help though.

@HamidSayeed

This comment has been minimized.

Copy link

HamidSayeed commented Aug 31, 2018

Thank you @kyle Hounslow @kylehounslow Thank you very very much !!!!

It really helped me .. Thank you again
I had similar problem @kaskavalci

@shibli2700

This comment has been minimized.

Copy link

shibli2700 commented Sep 16, 2018

What if i want to send some additional data along with the frame eg: name, id etc.

@frankie-yanfeng

This comment has been minimized.

Copy link

frankie-yanfeng commented Nov 8, 2018

Thanks, useful advice.

@Boulder67

This comment has been minimized.

Copy link

Boulder67 commented Dec 7, 2018

It will be really nice If script can be completely standalone/independent RESTful Web Services that can process the image along with some text data to go with it. regardless to what the client side language is. So, the client side and server side are completely separated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.