You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 02:25:03