首页 > 解决方案 > 将字节转换为图像

问题描述

我编写了一个接收图像并使用 Kmeans 的小型烧瓶应用程序,在返回之前降低质量。不幸的是,我正在努力处理我刚刚收到的上传图像。我设法在变量中以字节为单位获取图像,但在那之后,我就迷路了。我尝试使用 PIL,但 Image.frombytes 需要大小,并且每个图像的大小都会不同。

#!/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)

标签: pythonflask

解决方案


request.files['image']返回一个werkzeug.FileStorage对象,不一定是图像文件。但是让我们假设该文件确实是一个 JPEG 文件。在这种情况下,您应该将其视为 JPEG 文件,而不是图像对象。然后您可以通过缓冲区将其读入一个numpy数组,如下所示:


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)

此处获取元数据的更多信息(例如,文件是 jpg 还是 png):https ://pythonise.com/series/learning-flask/flask-uploading-files


推荐阅读