简体   繁体   中英

How to convert image file object to numpy array in with openCv python?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM