0

I am trying to make a face recognition API with Flask and deepface library. But I am not able to open the image it's giving me different errors. Please give me a solution.

Code:

@app.route('/detect', methods=['POST'])
def recognize():
    image_path = request.files.get('image')
    try:
        analysis = DeepFace.analyze(image_path)
        return jsonify(analysis)
    except Exception as e:
        return jsonify({'error': str(e)})

error

  "error": "object of type 'FileStorage' has no len()"

Tried to open the image

    with open(image_path, 'r') as image:
            analysis = DeepFace.analyze(image)
            return jsonify(analysis)

I get the error

{"errors": "expected str, bytes or os.PathLike object, not FileStorage"}

2 Answers2

0

I think image_path holds object of type FileStorage which knows location of a file and does not hold actual image data. First you need to load that image file and then try to analyze it.

Sharmiko
  • 543
  • 4
  • 21
0

A werkzeug FileStorage object has several methods as I've documented in another answer.

Sounds like you need to save the image to a temporary location first, then do the analysis.

I would create a directory called uploads on your server, then set this in the app config:

app.config['UPLOAD_FOLDER'] = 'uploads'

Then in your route, use the uuid.uuid4 function to create a temporary filename. Something like:


from uuid import uuid4

@app.route('/detect', methods=['POST'])
def recognize():

    tmp_fname = os.path.join(app.config['UPLOAD_FOLDER'], uuid4().__str__())

    image = request.files['image']
    image.save(tmp_fname)
    try:
        analysis = DeepFace.analyze(tmp_fname)
        return jsonify(analysis)
    except Exception as e:
        return jsonify({'error': str(e)})

This leaves the saved images on the filesystem, so you may wish to do some cleanup on this directory, or do something like os.remove('tmp_fname') after running the analysis.

I'm not sure whether Deepface.analyze accepts a stream as its first argument. The README suggests it only accepts a filename as a string. You could try doing Deepface.analyze(image.stream) to avoid having to deal with saving the temporary file (keep everything in memory instead), but this may not be supported.

v25
  • 7,096
  • 2
  • 20
  • 36