pythontensorflowflaskrequesttensorflow-serving

How to send an image that was sent with a post request to a model for prediction


I'm running a flask app that receives a base64 encoded image through a post request and should send it for classification. Unfortunately, this is where I come across an error. This is my code for making a post request:

def encode_image(img_path):

    with open(img_path, 'rb') as f:

        encoded_string = base64.b64encode(f.read())

    return encoded_string


def send_image(img_path):

    img = encode_image(img_path)

    data = {'imageBase64': img.decode('UTF-8')}

    r = requests.post(url, data = json.dumps(data))

send_image('/path/to/image.jpg')

And this is my flask app code:

@app.route('/', methods = ['POST'])
def predict():
    if request.method == 'POST':  
        base64img = request.data
    
        base64img += b'=' * (-len(base64img) % 4)
    
        img = base64.b64decode(base64img)

        img = image.load_img(BytesIO(img), target_size = (28, 28), color_mode = 'grayscale')
        img = Image.open(img)

        img = image.img_to_array(image.load_img(BytesIO(img)), target_size = (28, 28))
        payload = {
            'instances': [{'input_image': img.to_list()}]
        }

        r = request.post(url, json = payload)
        pred = json.loads(r.content.decode('utf-8'))

        return pred

The line img = image.load_img(BytesIO(img)) throws this error:

TypeError: expected str, bytes or os.PathLike object, not BytesIO

I'm not sure how to fix this, has anyone got any ideas?


Solution

  • Ok, I managed to do it like this:

    @app.route('/', methods = ['POST'])
    def predict():
        if request.method == 'POST':
            base64img = request.get_json()['img'].encode('utf-8')
    
            img = base64.b64decode(base64img)
            with open('imgtemp.png', 'wb') as f:
                f.write(img)
    
            img = cv2.imread('imgtemp.png', 1)
        
            img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    
            payload = {
                'instances': [{'input_image': img.tolist()}]
            }
    
            r = requests.post(url, json = payload)
            pred = json.loads(r.content.decode('utf-8'))
    
            return pred