gradio代码案例+效果图片
直接上代码:
import gradio as gr import numpy as np import torch from PIL import Image from ram.models import ram_plus from ram import inference_ram as inference from ram import get_transform import time # 加载模型 m_start = time.time() device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') transform = get_transform(image_size=384) model = ram_plus(pretrained='pretrained/ram_plus_swin_large_14m.pth', image_size=384, vit='swin_l') model.eval() model = model.to(device) m_end = time.time() print('model load time:{}'.format(m_end-m_start)) # 用于生成随机颜色的函数 def random_color(): return "#{:06x}".format(np.random.randint(0, 0xFFFFFF)) # Gradio的图像标签回调函数 def image_tagging(input_image): # 在这里添加你的图像标签生成代码 # 这里使用一个示例,你可以替换为你的模型输出 start = time.time() image = transform(input_image).unsqueeze(0).to(device) res = inference(image, model) labels = res[1].split(' | ') end = time.time() print('infer time:{}'.format(end-start)) # labels = ["标签1", "标签2", "标签3"] # 生成HTML代码,使用Flexbox布局自适应排列 label_html = '<div style="display: flex; flex-wrap: wrap;">' for label in labels: color = random_color() label_html += f'<div style="background-color: {color}; color: white; border-radius: 15px; padding: 10px; margin: 5px;">{label}</div>' label_html += '</div>' description_html = '<p style="font-size: 16px; color: #333;">这里是图片标签的输出结果</p>' return description_html+label_html # Gradio界面配置 iface = gr.Interface( fn=image_tagging, inputs=gr.Image(type="pil", label="点击上传图片"), outputs=gr.HTML(label="此图片包含的标签为"), live=False, title="智能图像标签体验网页", description = "上传图片以后,点击submit按钮,即可提取图片中的各种标签,赶紧试试吧!" ) # 启动Gradio界面 iface.launch(server_name="0.0.0.0",server_port=8089)
展示界面:
本文来自博客园,作者:海_纳百川,转载请注明原文链接:https://www.cnblogs.com/chentiao/p/17958458,如有侵权联系删除