Guilherme Richter
Guilherme Richter

Reputation: 113

Convert byte to a image

I wrote a small flask app that receives an image and using Kmeans, reduce the quality before returning it. Unfortunately I am struggling to process the image that I just receive as upload. I manage to get the image in bytes inside a variable, but after that, I just get lost. I tried to use PIL, but Image.frombytes require the size, and the size will be different for each image.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import numpy
from sklearn.cluster import KMeans
from flask import Flask, send_file, request

app = Flask(__name__)
COLOR_NUM = 64


@app.route('/', methods=['GET', 'POST'])
def index():
    return 'PygmaIOi'


@app.route('/convert', methods=['POST'])
def convert():
    if 'image' not in request.files:
        return 'No image!'
    image = request.files['image'].read()
    #   Original dimensions
    w = image.shape[0]
    h = image.shape[1]
    #   Reshape it
    image = image.reshape(w*h, 3)
    #   K-Means clusters
    kmeans = KMeans(n_clusters=COLOR_NUM)
    kmeans.fit(image)
    image = kmeans.cluster_centers_[kmeans.labels_]
    image = numpy.clip(image.astype('uint8'), 0, 255)
    #   Set native resolution
    image = image.reshape(w, h, 3)
    return send_file(image)


if __name__ == '__main__':
    #   Webserver
    app.run(debug=False)

Upvotes: 0

Views: 1443

Answers (1)

bkakilli
bkakilli

Reputation: 519

request.files['image'] returns you a werkzeug.FileStorage object, which is not necessarily an image file. But let's assume the file is indeed a JPEG file. In this case you should treat it as a JPEG file, not an image object. Then you can read it into a numpy array through a buffer as follows:


import io
from PIL import Image
import numpy as np

...

buffer = io.BytesIO()
request.files['image'].save(buffer)

image = np.array(Image.open(buffer, format='JPEG'))
# image is a numpy array. Eg. (H, W, 3)

More info here for obtaining the metadata (eg. whether the file is jpg or png): https://pythonise.com/series/learning-flask/flask-uploading-files

Upvotes: 1

Related Questions