1

I want to print out the mouse coordinate upon clicking on the displayed image. It is not a graph figure.

After looking through all online forum, I discovered they are all made for a graph figure and not displayed images. I'm surprised I couldn't find even one example.

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

# The usual way which I found online
fig = plt.figure() 
ax = fig.add_subplot(111) 
ax.plot(np.random.rand(10)) 

def onclick(event): 
     print("button=%d, x=%d, y=%d, xdata=%f, ydata=%f" %( 
         event.button, event.x, event.y, event.xdata, event.ydata)) 

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

# What I currently Have
img = mpimg.imread("my_img.jpg")
plt.imshow(img)

plt.show()
3
  • Are you looking to find the mouse coordinate relative to your screen or image? Commented Aug 2, 2019 at 2:00
  • If you are looking to get coordinates from image you can also try the trackpy module that does this. Commented Aug 2, 2019 at 2:01
  • Axios, it is relative to the image. It is actually displayed on the bottom right corner, I just need to have in my python code. Commented Aug 2, 2019 at 2:37

1 Answer 1

2

Matplot uses the same methods to display plot or image. You have to only find figure for displayed image.

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

def onclick(event): 
    print("button=%d, x=%d, y=%d, xdata=%f, ydata=%f" % ( 
         event.button, event.x, event.y, event.xdata, event.ydata)) 

img = mpimg.imread("image.jpg")
ax = plt.imshow(img)
fig = ax.get_figure()
cid = fig.canvas.mpl_connect('button_press_event', onclick) 

plt.show()

Instead of mpimg.imread() you can use plt.imread()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.