Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display the coordinates of the points clicked on the image in Google Colab?

I need to locate the mouse click location on an image in a google colab notebook. I tried the following script but nothing happened. The following code should work in Jupyter notebooks but it doesn't work on google colab:

import matplotlib
matplotlib.use('TKAgg')
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

f1 = 'sample.tif'

fig = plt.figure(figsize=(20,30))

img = mpimg.imread(f1)

def onclick(event):
    ix, iy = event.xdata, event.ydata
    print(ix, iy)

cid = fig.canvas.mpl_connect('button_press_event', onclick)

imgplot = plt.imshow(img)
plt.show()
like image 573
Mohammad Avatar asked Oct 31 '25 06:10

Mohammad


1 Answers

You need to use an interactive IPython backend, e.g. ipympl:

  1. Installation in Colab:
!pip install ipympl
from google.colab import output
output.enable_custom_widget_manager()
  1. setup matplotlib to use it:
%matplotlib ipympl
  1. test it:
import matplotlib
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

def onclick(event):
    ix, iy = event.xdata, event.ydata
    print(ix, iy)

cid = fig.canvas.mpl_connect('button_press_event', onclick)

Output:

enter image description here

like image 176
Stef Avatar answered Nov 02 '25 22:11

Stef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!