Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading image file (file storage object) using CV2

I am sending an image by curl to flask server, i am using this curl command

curl -F "[email protected]" http://localhost:8000/home

and I am trying to read the file using CV2 on the server side.

On the server side I handle the image by this code

@app.route('/home', methods=['POST'])
def home():
    data =request.files['file']
    img = cv2.imread(data)
    fact_resp= model.predict(img)
    return jsonify(fact_resp)

I am getting this error-

img = cv2.imread(data)
TypeError: expected string or Unicode object, FileStorage found

How do I read the file using CV2 on the server side?

Thanks!

like image 503
AKSHAYAA VAIDYANATHAN Avatar asked Nov 27 '17 16:11

AKSHAYAA VAIDYANATHAN


1 Answers

I had similar issues while using opencv with flask server, for that first i saved the image to disk and read that image using saved filepath again using cv2.imread()

Here is a sample code:

data =request.files['file']
filename = secure_filename(file.filename) # save file 
filepath = os.path.join(app.config['imgdir'], filename);
file.save(filepath)
cv2.imread(filepath)

But now i have got even more efficient approach from here by using cv2.imdecode() to read image from numpy array as below:

#read image file string data
filestr = request.files['file'].read()
#convert string data to numpy array
npimg = numpy.fromstring(filestr, numpy.uint8)
# convert numpy array to image
img = cv2.imdecode(npimg, cv2.CV_LOAD_IMAGE_UNCHANGED)
like image 179
flamelite Avatar answered Sep 28 '22 12:09

flamelite