Upload app.py
#1
by jmgbbi - opened
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748import gradio as gr
import numpy as np
import cv2
from PIL import Image
import onnxruntime as ort
import requests
from io import BytesIO
# 加载 ONNX 模型
model_path = "models/model.onnx"
session = ort.InferenceSession(model_path)
def remove_bg(input_img):
# 如果输入是 URL
if isinstance(input_img, str):
response = requests.get(input_img)
input_img = Image.open(BytesIO(response.content)).convert("RGB")
# PIL 转 numpy
img = np.array(input_img)
h, w, _ = img.shape
# ONNX 输入预处理(512x512)
img_resized = cv2.resize(img, (512, 512))
img_input = img_resized.astype(np.float32) / 255.0
img_input = np.transpose(img_input, (2, 0, 1))[np.newaxis, :, :, :]
# 模型推理
output = session.run(None, {'input': img_input})[0]
mask = cv2.resize(output[0, 0], (w, h))
mask = (mask > 0.5).astype(np.uint8) * 255
# 合成带透明通道图片
b, g, r = cv2.split(img)
alpha = mask
rgba = cv2.merge([r, g, b, alpha])
return Image.fromarray(rgba)
# Gradio 接口
iface = gr.Interface(
fn=remove_bg,
inputs=gr.Image(type="pil", label="Upload Image or enter URL"),
outputs=gr.Image(type="pil", label="Background Removed"),
title="MODNet Tiny Background Removal",
description="Upload an image or enter a URL to remove the background."
)
iface.launch()app.pyAdded+48