python - 将字节转换为图像
问题描述
我编写了一个接收图像并使用 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)
解决方案
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
推荐阅读
- javascript - React 上下文和备忘录
- bash - Bash 如何按顺序运行多个 wget(非并行)并删除 wget 文件以进行速度测试
- python - ctypes 改变结构值
- imagemagick - 如何在imagemagick中剪出一个矩形(即设置为透明)?
- python - 使用数据集的均值和标准差对图像进行归一化
- node.js - 在猫鼬和Nodejs中删除父对象时如何删除对象引用(子对象)
- php - 数组中的VS Code PHP Intelephense对象未向->运算符显示属性和函数
- c# - 在 C# 中的列表中设置获取类
- python - Python Turtle 图形不等屏
- python - 在 Telethon 中,我只想在用户按下设置我的地址按钮后获取用户的加密地址