使用Gradio部署HuggingFace目标检测Transformer模型遇报错求助
问题分析与解决方案
第一个错误原因
Gradio的gr.Interface.from_pipeline()方法并未内置支持HuggingFace的ObjectDetectionPipeline类型,直接传入目标检测管道会触发Unsupported pipeline type错误,必须通过自定义函数封装模型调用逻辑。
第二个错误原因
自定义函数中使用"label"作为输出组件不合适:目标检测管道返回的是包含边界框坐标、类别标签、置信度的字典列表(格式示例:[{"box": {"xmin": 10, "ymin": 20, "xmax": 100, "ymax": 150}, "label": "cat", "score": 0.95}, ...]),而label组件仅能显示纯文本标签,无法解析和展示边界框信息,导致预测时报错。
修正后的完整代码
import gradio as gr from transformers import pipeline # 提前初始化目标检测管道,避免每次调用重复加载模型 obj_detect = pipeline("object-detection") def object_detector(image): # 调用模型得到检测结果 results = obj_detect(image) # 转换结果格式为Gradio Image组件可识别的标注格式 annotations = [] for result in results: box = result["box"] annotations.append({ "label": f"{result['label']} ({round(result['score'], 2)})", "bbox": [box["xmin"], box["ymin"], box["xmax"], box["ymax"]] }) # 返回原始图像和标注信息 return image, annotations # 构建Interface:输入为图像,输出为带标注的图像 app = gr.Interface( fn=object_detector, inputs=gr.Image(type="pil"), outputs=gr.Image(type="pil", label="检测结果", show_label=True), title="目标检测演示", description="上传图像即可识别其中的物体并标注边界框" ) app.launch(share=True)
关键修正点说明
- 提前初始化管道:将
obj_detect = pipeline("object-detection")放在函数外部,避免每次预测都重新加载模型,提升性能。 - 输出组件调整:使用
gr.Image作为输出组件,并将检测结果转换为包含label和bbox的字典格式,Gradio会自动在图像上绘制边界框和标签。 - 修正拼写错误:原代码中
Import应为小写import,这是基础语法错误,会导致代码无法运行。
内容的提问来源于stack exchange,提问作者Ifeanyi Idiaye
相关产品推荐
相关产品推荐

