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()
                You need to use an interactive IPython backend, e.g. ipympl:
!pip install ipympl
from google.colab import output
output.enable_custom_widget_manager()
%matplotlib ipympl
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:

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