Python 将字节转换为图像
我编写了一个小烧瓶应用程序,它接收图像并使用Kmeans,在返回图像之前降低质量。不幸的是,我正在努力处理刚刚上传的图像。 我设法在一个变量中获得以字节为单位的图像,但在那之后,我就迷失了方向。我尝试使用PIL,但Image.frombytes需要大小,并且每个图像的大小都不同Python 将字节转换为图像,python,flask,Python,Flask,我编写了一个小烧瓶应用程序,它接收图像并使用Kmeans,在返回图像之前降低质量。不幸的是,我正在努力处理刚刚上传的图像。 我设法在一个变量中获得以字节为单位的图像,但在那之后,我就迷失了方向。我尝试使用PIL,但Image.frombytes需要大小,并且每个图像的大小都不同 #!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy from sklearn.cluster import KMeans from flask imp
#!/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)
request.files['image']
返回一个werkzeug.FileStorage
对象,该对象不一定是图像文件。但我们假设该文件确实是一个JPEG文件。在这种情况下,应将其视为JPEG文件,而不是图像对象。然后可以通过缓冲区将其读入numpy数组,如下所示:
输入io
从PIL导入图像
将numpy作为np导入
...
buffer=io.BytesIO()
request.files['image'].save(缓冲区)
image=np.array(image.open(buffer,format='JPEG'))
#图像是一个numpy数组。例(H、W、3)
获取元数据的更多信息(例如,文件是jpg还是png):
- PIL支持的格式:
docs:werkzeug.FileStorage