Gradio Image组件select事件无响应,点击无法触发问题求助
问题排查与修复
核心原因
Gradio的gr.Image组件默认未显式开启可选择交互配置,导致select事件无法被触发,这就是你点击无反应、控制台不打印"CLICKED"的根本原因。
修复步骤
1. 开启Image组件的选择交互功能
修改input_img的定义,添加interactive=True和selectable=True参数,确保组件允许点击选择:
input_img = gr.Image(label="Input", type="numpy", interactive=True, selectable=True)
2. 修正坐标映射逻辑
原代码中evt.index的坐标顺序与numpy图像索引存在混淆,evt.index返回的是(x, y)(对应图像宽、高方向),而numpy图像的索引是(y, x)(行、列),修正get_click_coords函数:
def get_click_coords(img, evt: gr.SelectData): print("CLICKED") global clicked_points out = img.copy() if len(clicked_points) < 5: # 转换为numpy图像的(y, x)索引 y, x = evt.index[1], evt.index[0] clicked_points.append((y, x)) # 绘制每个点击点的圆形 for center in clicked_points: out = draw_circle_on_img(out, center, radius=4, color=[0, 255, 255]) return out, out # 返回更新后的图像给两个组件,原代码返回原始图不符合预期
3. 修复重置事件的输出目标
原upload事件中,重置后的图像只更新了input_img,需要同步更新output_img:
input_img.upload(reset, [input_img], [input_img, output_img])
完整修复后代码
import gradio as gr import numpy as np # 存储点击点的全局列表 clicked_points = [] def draw_circle_on_img(img, center, radius=10, color=[255, 0, 0]): """在图像上绘制指定半径和颜色的圆形""" y, x = center height, width, _ = img.shape rr, cc = np.ogrid[:height, :width] dist = (rr - y) ** 2 + (cc - x) ** 2 mask = dist <= radius ** 2 img[mask] = color return img def get_click_coords(img, evt: gr.SelectData): print("CLICKED") global clicked_points out = img.copy() if len(clicked_points) < 5: y, x = evt.index[1], evt.index[0] clicked_points.append((y, x)) # 绘制所有已点击的点 for center in clicked_points: out = draw_circle_on_img(out, center, radius=4, color=[0, 255, 255]) return out, out def reset(img): print("RESET") global clicked_points clicked_points = [] return img, img with gr.Blocks() as demo: with gr.Row(): input_img = gr.Image(label="Input", type="numpy", interactive=True, selectable=True) output_img = gr.Image(label="Image with Clicks", type="numpy") input_img.select(get_click_coords, [input_img], [input_img, output_img]) input_img.upload(reset, [input_img], [input_img, output_img]) if __name__ == "__main__": demo.launch()
额外说明
- 若使用Gradio 3.x早期版本,
selectable参数可能不存在,此时仅保留interactive=True即可,旧版本中该参数已包含选择功能 - 修复后运行代码,鼠标悬停图像会显示目标光标,点击后控制台打印"CLICKED",同时图像上会出现青色圆形标记
内容的提问来源于stack exchange,提问作者cukkoo
相关产品推荐
相关产品推荐

