11

I am developing API to upload Image using Flask. After uploading i want to modify image using openCV, As openCV requires numpy array object to i have file object, how do i convert to numpy array? Here is my code

@app.route('/upload', methods=['POST'])
def enroll_user():
    file = request.files['fileName']
    # file.save(os.path.join(file.filename))
    return response

Edit: updated code

@app.route('/upload', methods=['POST'])
    def enroll_user():
        file = request.files['fileName']
        response = file.read()
        # file.save(os.path.join(file.filename))
        return response

I want to convert file to cv2 frame as i get with below code

ret, frame = cv2.imread(file)

One way is to write image to disk and read again with cv2.imread but i don't want to do that because it will be time consuming. So is there any way to convert to cv2 frame from file object?

Thanks

4
  • 1
    Something like this? Commented Sep 24, 2019 at 14:10
  • Could you share the code sending the http request please? Commented Sep 24, 2019 at 15:07
  • OpenCV image object is numpy object, generally with dtype np.uint8. Commented Sep 24, 2019 at 16:51
  • @QuangHoang You are right, OpenCV image object is numpy object, but i want to convert uploaded jpg file to OpenCV image object. Commented Nov 11, 2019 at 13:12

2 Answers 2

4

If you effectively have the contents of a JPEG/PNG file in your variable called response, I think you can do:

frame = cv2.imdecode(response)

Or, you may need to do:

frame = cv2.imdecode(np.fromstring(response, np.uint8), cv2.IMREAD_COLOR)

Failing that, another way is like this:

from io import BytesIO
from scipy import misc

frame = misc.imread(BytesIO(response))
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your reply, I have tried with imdecode, but it requires flag as second argument so i have passed cv2.IMREAD_COLOR but now i am getting Error: frame = cv2.imdecode(file, cv2.IMREAD_COLOR) TypeError: buf is not a numpy array, neither a scalar
I also tried your second method,which gives me a following Error: frame = misc.imread(BytesIO(img)) TypeError: a bytes-like object is required, not 'FileStorage'
I updated my answer, please try new, second option. Thank you.
Thanks, the updated option works for me, but before that i need to read the file which i haven't done. As in my updated question.
Cool. Glad we got you up and running - sorry it took me so long. Good luck with your project!
0

If the file is in read-byte mode (which means mode='rb') in your case, then numpy.frombuffer() also works, for example :

file = request.files['fileName']
frame = cv2.imdecode(np.frombuffer(file.read(), numpy.uint8), cv2.IMREAD_COLOR)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.