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

如何在Google Colab中显示图片上点击点的坐标?

在Google Colab中实现图片点击位置定位的解决方案

你的代码在Jupyter中正常运行但Colab无效,核心原因是Colab的浏览器环境不支持桌面端的Matplotlib后端(如TKAgg),默认的inline后端是非交互式的,无法响应鼠标点击事件。以下是适配Colab的修改方案:

步骤1:启用交互式Matplotlib后端

Colab需要使用交互式后端才能捕获鼠标事件,先执行以下命令:

!pip install ipympl
%matplotlib widget

步骤2:修改后的代码

移除桌面端后端配置,添加事件有效性判断避免报错:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

# 确保sample.tif已上传到Colab文件系统
f1 = 'sample.tif'

fig = plt.figure(figsize=(20,30))
img = mpimg.imread(f1)

def onclick(event):
    # 仅处理图片区域内的点击
    if event.xdata is not None and event.ydata is not None:
        ix, iy = event.xdata, event.ydata
        print(f"点击坐标:x={round(ix, 2)}, y={round(iy, 2)}")

# 绑定点击事件
cid = fig.canvas.mpl_connect('button_press_event', onclick)

plt.imshow(img)
plt.show()

注意事项

  • 确保sample.tif已上传到Colab:可通过左侧文件面板上传,或用from google.colab import files; files.upload()代码上传。
  • 运行代码后会出现交互式图片,点击图片区域即可在控制台看到坐标输出。

内容的提问来源于stack exchange,提问作者Mohammad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 22:16:31