将Gradio应用转为Flask API:如何处理图片得到gr.Image相同返回值
将Flask上传的图片转为与Gradio gr.Image(type="pil")一致的PIL对象
Gradio的gr.Image(type="pil")返回的是RGB模式的PIL.Image对象,要在Flask里实现完全一致的预处理,只需对request.files获取的文件做两步处理:读取文件流并转为PIL图像、统一转换为RGB模式(对齐Gradio默认行为)。
具体代码实现
from PIL import Image from flask import Flask, request app = Flask(__name__) @app.route('/process-images', methods=['POST']) def process_images(): # 获取上传的布料图片 cloth_file = request.files.get('cloth_image') if not cloth_file: return {"error": "cloth_image 参数必填"}, 400 # 预处理为与Gradio一致的PIL对象 try: cloth_image = Image.open(cloth_file.stream).convert('RGB') except Exception as e: return {"error": f"布料图片无效: {str(e)}"}, 400 # 同理处理蒙版图片 mask_file = request.files.get('cloth_mask_image') if not mask_file: return {"error": "cloth_mask_image 参数必填"}, 400 try: cloth_mask_image = Image.open(mask_file.stream).convert('RGB') except Exception as e: return {"error": f"蒙版图片无效: {str(e)}"}, 400 # 此处可直接复用原Gradio中基于PIL图像的业务逻辑 # ... 你的处理代码 return {"status": "success"}
关键细节说明
request.files['cloth_image']是Flask的FileStorage对象,通过stream属性可直接读取文件内容,无需保存到本地。- Gradio的
gr.Image(type="pil")默认会自动将任何格式的图像转为RGB模式,因此必须添加.convert('RGB')才能和Gradio的输出完全匹配。 - 若你的Gradio组件指定了
mode参数(比如mode="RGBA"),只需将convert的参数改为对应模式即可。
内容的提问来源于stack exchange,提问作者JwCwn
相关产品推荐
相关产品推荐

